I have nodejs server file server.js
const express = require('express');
const session = require('express-session');
const router = express.Router();
const https = require('https');
const app = express();
const api1 = require('./apps/routes/api1')( app,router);
const api2 = require('./apps/routes/api2')( app,router);
app.use('/api1', api1);
app.use('/api2', api2);
https.createServer(options, app).listen(3500 , function (err) {
if (err) {
console.log(err)
} else
{
console.log("server is running!")
}
});
now api1.js file
module.exports = function (app, router) {
router.post("/test",function(res,res){
res.json({
data:"done"
});
})
return router;
})
now api2.js file
module.exports = function (app, router) {
router.post("/production",function(res,res){
res.json({
data:"done"
});
})
return router;
})
Now when i call api
/api1/test
then response is
{
data:"done"
}
Now when i call api
/api2/test
then response is again
{
data:"done"
}
my question is since prefix for test api is api1 so if i call using /api2/test this should return 404 not found
Please help me i am confused here!
Change api1.js from:
module.exports = function (app, router) {
router.post("/test",function(res,res){
res.json({
data:"done"
});
})
return router;
})
to:
const router = express.Router();
module.exports = function (app) {
router.post("/test",function(res,res){
res.json({
data:"done"
});
})
return router;
})
and similar in api2.js.
You're passing router as reference, it means, if you adding path to the router, it is added everywhere when this router is used.