I am building a web application using the Node JS Express JS framework. Now, I am trying to add a prefix to all the routes of my application. But it is not working.
This is how I did it.
let express = require('express');
let app = express();
const apiRouter = express.Router()
apiRouter.use('/api', () => {
app.get('/auth', (req, res) => {
res.send("Auth route")
})
return app;
})
When I go to the '/api/auth' in the browser, I am not getting the expected response. I am getting the following error.
Cannot GET /api/auth
What is wrong with my code and how can I fix it?
It is because app.use
is to add middleware(to specific request you add for particular path) to your request and to respond by matching the exact path to it. You can read more details here it is a very detailed thread.
let express = require('express');
let app = express();
const apiRouter = express.Router();
//create route file which will handle the exact match for it;
const apiRouteHandler = require('path');
app.use('/api', apiRouteHandler)
Sample apiRouteHandler
const express = require('express');
const router = express.Router();
router.get('/auth', function(req, res){
res.send('GET route on things.');
});
//export this router to use in our index.js
module.exports = router;
Cannot GET /api/auth
This errors comes in because app unable to match this route anywhere as in the middleware app.get
won't we invoked like this. You need to create a route handler for that and then it routing mechanism of express will pass on to the correct handler in the route file.