Home > Back-end >  How to route all routes through router.js file with Express?
How to route all routes through router.js file with Express?

Time:05-05

I have app.js file where I route /api routes to api.js file:

const api = require("./src/rest/api")
......
app.use("/api", api)

I am planning to to do all routing in router.js file, so router.js file would look like this:

app.all("/api", api)
app.all("/status", status)

How can I achieve this? I tried to use app.use("/", router) in app.js file but when I receive request in router.js file, the path doesn't anymore exist.

CodePudding user response:

main.js

const router = require('router.js')

app.use('/api', router)

router.js

const router = express.Router()

// path: /api/status
router.get('/status', (req, res, next)=>{
 // do something here
}) 

module.exports = router
  • Related