如何将 req.params 作为参数传递给中间件函数?
How to pass req.params as an an argument to a middleware function?
我正在尝试找出一种在我的中间件中使用 req.params 作为参数的方法。以这个(明显损坏的)代码为例:
router.post('/:myParam', checkSchema(schemas[req.params.myParam]), async (req, res, next) => {
// do stuff
})
我的目标是使用 express-validator
并根据传递的参数加载动态模式。上面的代码显然是错误的,因为我还没有访问 req 变量的范围,我只是想说明我要完成的事情。
如果您知道前面可能的参数,您可以执行以下操作:
router.post("/:myParam", checkSchema("soccer"), async (req, res, next) => {});
//checkSchema.JS
const soccerSchema = require("../schemas/soccerSchema");
const swimmingSchema = require("../schemas/swimmingSchema");
module.exports = function (schemaName) {
return (req, res, next) => {
const schemas = { soccer: soccerSchema, swimming: swimmingSchema };
//You can access it here schemas[schemaName]
console.log(schemas[schemaName]);
next();
};
};
您可以直接在 checkSchema
中间件中调用 schemas(req.params.myParam)
,因为中间件可以访问请求对象。
我正在尝试找出一种在我的中间件中使用 req.params 作为参数的方法。以这个(明显损坏的)代码为例:
router.post('/:myParam', checkSchema(schemas[req.params.myParam]), async (req, res, next) => {
// do stuff
})
我的目标是使用 express-validator
并根据传递的参数加载动态模式。上面的代码显然是错误的,因为我还没有访问 req 变量的范围,我只是想说明我要完成的事情。
如果您知道前面可能的参数,您可以执行以下操作:
router.post("/:myParam", checkSchema("soccer"), async (req, res, next) => {});
//checkSchema.JS
const soccerSchema = require("../schemas/soccerSchema");
const swimmingSchema = require("../schemas/swimmingSchema");
module.exports = function (schemaName) {
return (req, res, next) => {
const schemas = { soccer: soccerSchema, swimming: swimmingSchema };
//You can access it here schemas[schemaName]
console.log(schemas[schemaName]);
next();
};
};
您可以直接在 checkSchema
中间件中调用 schemas(req.params.myParam)
,因为中间件可以访问请求对象。