node.jsexpressexpress-router

How to route all routes through router.js file with Express?


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.


Solution

  • 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