NodeJS回调如何与路由/控制器一起工作?

时间:2017-06-01 16:04:18

标签: javascript node.js

我试图了解你们如何使用回调,以及为什么我一直在使用

TypeError: callback is not a function

好的,这是我的路由器:

// getPriceRouter.js
router.post('/getPrice', function(req, res) {
    priceController.getPrice(req, res);
}   

这是我的控制者:

// getPriceController.js
exports.getPrice = function(req, callback) {
    callback( { error:false, data:"HELLO" } );
}

这一直给我错误回调不是函数 (这与export.有关吗?​​)

我使用下面的建议再试一次......

// getPriceRouter.js
router.post('/getPrice', function(req, res) {
    priceController.getPrice(req, function(result) {});
        console.log("getPrice returned:" + result);
        res.json(result);
});

但现在我得到结果未定义

如果我然后放一个res=result然后我得将循环结构转换为JSON

4 个答案:

答案 0 :(得分:2)

您的getPrice函数需要一个函数(这是一个回调)作为第二个参数。但是你在路由器中发送res(这不是一个功能)。

可以使用函数替换res来纠正:

// getPriceRouter.js
router.post('/getPrice', function(req, res) {
    priceController.getPrice(req, function(result) {
      // result is now an object with error and data properties.
      // and you can still use req and res
      return res.json(result)
      // It's better to place return since there is no operation left to do with this request.
    });
}

答案 1 :(得分:0)

您需要将回调函数作为第二个参数传递给priceController.getPrice,例如

 priceController.getPrice(req, function(result) {
   if (result.error) { throw result.error; }
   res.send(result.data)
 });

答案 2 :(得分:0)

回调是一个功能。这意味着如果你在代码需要一个函数时传递一个对象,它就会抛出这个错误。

好的,基本上,假设你有以下功能:

function print(paramToPrint){
    if (paramToPrint !== undefined){
        console.log(paramToPrint)
    } else {
        console.log('Error, paramater is undefined!')
    }
}

另外这个功能:

function selectItems(param1, callback){
    var double = param1 * 2;
    callback(double)
}

现在,我们将函数selectItems调用函数print作为回调

selectItems(2, print);

并且打印到控制台的输出将为4。你明白这个吗?

对于更多的信息,我建议你检查一下,对我来说似乎很好! http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

编辑:我实际上没有回答你的问题,但我希望我能帮助你理解一些回调:)

答案 3 :(得分:-1)

您正在将req,res对象传递给控制器​​方法。

'getPrice'函数的参数中的回调实际上是指'res'对象,它不是一个函数。在你的getPrice方法中,你用参数调用这个'res'对象,这是不对的,因为它不是一个函数。因此错误'回调不是函数'。