javascript - NodeJS 回调如何与路由/ Controller 一起工作?

标签 javascript node.js

我试图了解你们如何使用回调,以及为什么我不断收到

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/

相关文章:

node.js - 在 mongoose/mongodb/node 中使用异步回调循环

javascript - 为什么修改 array.slice() 也会改变原始数组?

javascript - 在 javascript 上测试私有(private)成员

jquery - 让 Node.js 中的 http.request 适用于浏览器

javascript - 如何将 props 传递给 Material-ui 风格的组件?

javascript - 我无法返回 axios 请求的响应

javascript - 如何使用javascript根据输入值隐藏元素?

javascript - 动态更新 d3.js 树形图

javascript - Angular 不显示 html 页面

node.js - 如何添加外键来 Sequelize 模型