如何在Express路由中将参数发送到中间件功能? [英] How to send parameters to the middleware functions in Express routing?
问题描述
我正在研究一个MEAN项目,其中有一些已定义的api路由,如下所示:
I am working on a MEAN project where we have some defined api routes like this:
//products.controller.js
var express = require('express');
var router = express.Router();
const m = require('../../middlewares');
router.get('/products', [m.functionA, m.functionB, m.functionC], getProducts);
router.post('/products', [m.functionA, m.functionB, m.functionC], addNewProduct);
module.exports = router;
function getProducts(req, res) {
//code
}
function addNewProduct(req, res) {
//code
}
..............
..............
//middlewares.js
function functionA(req, res, next) {
//code
}
function functionB(req, res, next) {
//code
}
function functionC(req, res, next) {
//code
}
现在我可以在其中访问req,res和next.如何将自定义参数传递给这些中间件功能?
Here now I can access req, res and next. How can I pass custom parameters to these middleware functions?
我查看了一些SO问题和其他文章,发现我可以这样做:
I looked over some SO questions and other articles and found that I can do like this:
[m.functionA('data'), m.functionB('data'), m.functionC('data')]
但是在执行此操作时,我收到错误消息,要求未定义res.
But on doing this, I get error that req, res are not defined.
任何人都可以帮助/建议如何实施此方法. 让我知道是否需要在此处添加其他详细信息.
Can anyone please help/suggest how to implement this. Let me know if any other details need to be added here.
推荐答案
如果要使用m.functionA('data')
,Express中间件中的常见范例是创建一个将参数作为参数的函数并返回中间件功能:
If you want to use m.functionA('data')
, a common paradigm amongst Express middleware is to create a function that takes the parameter as an argument, and returns a middleware function:
function functionA(customParameter) {
return function(req, res, next) {
// code
}
}
内部函数(返回的内部函数)可以访问customParameter
和req/res/next
.
The inner function (the one being returned) has access to customParameter
as well as req/res/next
.
这篇关于如何在Express路由中将参数发送到中间件功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!