【发布时间】:2016-11-07 12:08:37
【问题描述】:
所以我正在向我的 Express 搜索路由器发出一个 post 请求,在该路由器中我使用 node-fetch 模块来调用远程 api:
var fetch = require('node-fetch');
router.route('/search')
//Performs Job Search
.post(function(req, res){
var area = req.body.area;
fetch('https://api.indeed.com/ads/apisearch?publisher=*********&l=' + area)
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
})
我在客户端使用 angular 1 来调用路由器并解析返回的 json:
$scope.search = function(){
$http.post('/api/search', $scope.newSearch).success(function(data){
if(data.state == 'success'){
//perform JSON parsing here
}
else{
$scope.error_message = data.message;
}
});
}
我刚刚开始使用 MEAN 堆栈,对 Promise 的工作原理只有一个模糊的概念。所以我的问题是我的角度搜索函数没有得到我想从远程 API 调用返回的 JSON 字符串。而是将数据参数设置为我的页面 html。最终,我在 .then() 子句中设置的断点被命中,我的 json 被返回。所以我的问题是,当 JSON 值最终返回时,如何使用 Angular 获取它们????
【问题讨论】:
-
您的 post 函数没有返回响应。你不应该在第二个
then声明中使用res.send(json)吗? -
当我在我的 .post 函数中设置断点时,它会走到函数的末尾,然后在调用 then 函数之前返回到客户端。最终,我的 .then 函数中的断点被击中并返回,但不确定我的角度函数已经运行完成的位置。我尝试了您的解决方案,但出现以下错误: UnhandledPromiseRejectionWarning: Unhandled Promise Rejection (rejection id: 2): Error: Can't set headers after they are sent.
-
啊,你已经有 res.json 了。所以你不需要 res.send。
标签: angularjs node.js api express mean-stack