How to send parameters to the middleware functions in Express routing?

最后都变了- 提交于 2020-01-22 15:34:05

问题


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
}

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')]

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.


回答1:


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
  }
}

The inner function (the one being returned) has access to customParameter as well as req/res/next.




回答2:


You could call the function with the arguments you like you using apply

function getProducts(list) {
  console.log(list);
}

getProducts.apply(null,['foo','bar'])


来源:https://stackoverflow.com/questions/46240248/how-to-send-parameters-to-the-middleware-functions-in-express-routing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!