我试图了解你们如何使用回调,以及为什么我不断收到
TypeError: callback is not a function
好的,这是我的路由器:
// getPriceRouter.js
router.post('/getPrice', function(req, res) {
priceController.getPrice(req, res);
}
这是我的 Controller :
// getPriceController.js
exports.getPrice = function(req, callback) {
callback( { error:false, data:"HELLO" } );
}
这一直给我错误回调不是函数
(这与导出有关吗?
?)
我根据下面的建议再次尝试了...
// getPriceRouter.js
router.post('/getPrice', function(req, res) {
priceController.getPrice(req, function(result) {});
console.log("getPrice returned:" + result);
res.json(result);
});
但现在我得到结果未定义
如果我然后输入 res=result
,那么我会得到ConvertingcircularstructtoJSON
最佳答案
您的 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.
});
}
关于javascript - NodeJS 回调如何与路由/ Controller 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44312347/