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
}
Run Code Online (Sandbox Code Playgroud)
..............
//middlewares.js
function functionA(req, res, next) {
//code
}
function functionB(req, res, next) {
//code
}
function functionC(req, res, next) {
//code
}
Run Code Online (Sandbox Code Playgroud)
Here now I can access req, res and next. How can I pass custom parameters to these middleware functions?
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')]
Run Code Online (Sandbox Code Playgroud)
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中间件中的一个常见范例是创建一个将参数作为参数并返回中间件函数的函数:
function functionA(customParameter) {
return function(req, res, next) {
// code
}
}
Run Code Online (Sandbox Code Playgroud)
内部函数(正在返回的函数)可以访问customParameter以及req/res/next。
| 归档时间: |
|
| 查看次数: |
1659 次 |
| 最近记录: |