【问题标题】:Unable to get a JSON response from my express router using node-Fetch module无法使用 node-Fetch 模块从我的快速路由器获得 JSON 响应
【发布时间】: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


【解决方案1】:

你能试试这样的吗?

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(result) {
            res.json(result);
            //or possibly res.send(result), depending on what indeed responds with
        })
    })

【讨论】:

    【解决方案2】:

    原来我忘记了我有中间件,如果用户在执行搜索时未通过身份验证,他们将被重定向到登录页面。所以我得到了这个登录页面返回的一堆 html,而不是我的 json。仍然让我感到困惑的是,如果我在到达此功能之前被重定向,为什么我的搜索功能中的断点会被命中。

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 2019-10-03
      • 2018-07-12
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      相关资源
      最近更新 更多