0

I have a file called index.js, which is my main file. I also made a file called router.js for the routing. I am trying to import the router.js module into the index.js file and run it as soon as the index.js is run.

This is the code inside of router.js:

const express = require('express')
const app = express()

app.get('/users',function(req,res,next){
    res.json([
        {id: 1, name: 'Jorge'},
        {id: 2, name: 'Emanuella'}      
    ])
})

And this is my index.js file:

const express = require('express')
const app = express()
const port = 5000
const router = require('./router')

app.listen(port, () => console.log(`App listening on port ${port}!`))

When I do console.log(router), I get an empty object.

I want the router to run when the index.js starts working. How can I achieve this?

0

1 Answer 1

3

You have to export app from router.js:

 module.exports = app;

Also, app should really be an Express router:

const app = express.Router(); 
Sign up to request clarification or add additional context in comments.

3 Comments

i would also change the name of the export from app to router. just a personal thing but i find it helps
I am getting an error saying Cannot GET /users
You have to mount the router.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.