是否可以将已定义的函数作为参数express.post()

时间:2019-03-26 12:38:10

标签: javascript node.js express

我有此代码,它工作正常。是否可以将已定义的函数作为参数express.post()传递。

const exs = require('express');
const exs_r = exs.Router();

router.post('/click', function(res, res) {
   //Do something
});

我想问你有没有可能,所以我可以像下面这样调用一个定义的函数:

router.post('/click', def_myfunc(res, res));
<br />
function def_myfunc (res, res)
{
    // do something
}

或者听起来更合理:

router.post('/click', function(res, res) {
   def_myfunc (res, res);
});


function def_myfunc (res, res)
{
    // do something
}

4 个答案:

答案 0 :(得分:2)

只需传递函数 reference 作为参数,而不是调用它

更改:

router.post('/click', def_myfunc(res, res));

收件人

router.post('/click', def_myfunc);

答案 1 :(得分:1)

只是

router.post('/click', def_myfunc);

function def_myfunc (req, res)
{
// do something
}

答案 2 :(得分:0)

您可以执行以下操作。

router.post('/click', def_myfunc);

function def_myfunc (res, res)
{
  // do something
}

答案 3 :(得分:0)

首先,您在参数(res)中输入错误。不是

router.post('/click', function(res, res) {
  //Do something
});

但是(req,res)

router.post('/click', function(req, res) {
  //Do something
});

话虽如此,正如上面其他人所述,只需按如下方式传递函数的引用即可:

function def_myfunc(req, res) {
  // whatever
}
router.post('/click', def_myfunc);
相关问题