I'm trying to add optional parameters to Express in all of my routes. Here is a part of my code:
const express = require('express');
const bodyParser = require('body-parser');
const apiRoutes = require('./routes/apiRoutes');
const app = express();
const port = process.env.PORT || 3000;
app.use(
'/api/:param?',
bodyParser.json({ limit: '50mb' }),
bodyParser.urlencoded({ extended: false, parameterLimit: 50000 }),
apiRoutes,
);
const server = app.listen(port, () => {
console.log(`Server is started on port *:${port}`);
});
I have all of my routes in apiRoutes file defined like:
router.get('system/versionInfo', async (req, res) => {
console.log('return Version info');
});
router.get('system/info', async (req, res) => {
console.log('return system info');
});
I would like the param?
to be optional so sometimes will be passed sometimes not. Now if I do not pass that param
, the routes are returning 404 error (Not Found). If I pass it, all is working fine.
So for example if I run:
'/api/test/system/versionInfo'
all is fine, but if I run
'/api/system/versionInfo'
it returns 404. I would like in both cases to return valid route.
Since express will go over all routes looking for a match, you can pass your apiRoutes
to multiple app.use()
calls, like this:
in apiRoutes.js:
router.get('system/info', async (req, res) => {
console.log('return system info');
});
in app.js:
app.use('/api/:param?',
(req, res, next) => {
if (req.params.param == "test") console.log("test param detected");
next();
},
apiRoutes,
);
app.use('/api', apiRoutes);
The /api/test/system/info
route will match the first rule, the api/system/info
route will match the second rule.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.