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?

Grigory Volkov
  • 472
  • 6
  • 26

1 Answers1

3

You have to export app from router.js:

 module.exports = app;

Also, app should really be an Express router:

const app = express.Router(); 
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151