【问题标题】:Get data using node-fetch using a function使用函数使用 node-fetch 获取数据
【发布时间】:2017-12-14 06:08:38
【问题描述】:

我正在尝试使用 node-fetch 通过 get 调用获取数据。

// Other code

fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
.then(function(data) {
    return data.json();
})
.then( function(result){
    res.send(result);
});

直到这里数据被成功渲染。我想用函数调用替换这段代码,以便它可以被重用。

我试过了:

function getDataFromUrl(){
    fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
    .then(function(data) {
        return data.json();
    }).then( function(result){
        return result;
    });
}

打电话给getDataFromUrl(),却一无所获。

也试过了:

function getDataFromUrl(){
    return fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
    .then(function(data) {
        return data.json();
    }).then( function(result){
        console.log(result); // prints desired data
        return result;
    });
}

并在浏览器中获得{}

请帮助我(一个节点学习者)从错误中恢复过来。

【问题讨论】:

    标签: node.js nodes node-fetch


    【解决方案1】:

    我使用 async 和 await 来解决这个问题。下面是包含 fetch 调用的函数:

    const externalServiceCall = async (statusRequest, requestContext) => {
    
        console.log(finalUrl);
    
        const res = await fetch(finalUrl,
            {method: "GET", headers: headers})
            .then(res => res);
    
        return res;
    }
    

    然后在我做的调用函数中

    const externalResponse = await externalServiceCall(statusRequest, requestContext)
    

    注意:这个调用函数也应该是async

    【讨论】:

      【解决方案2】:

      以这种方式定义你的函数:

      function getDataFromUrl(resp){
          fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
          .then(function(data) {
              return data.json();
          }).then(function(parsed){
              resp(parsed);
          });
      }
      

      并以这种方式调用:

      getDataFromUrl(function(resp){
          res.send(resp);
      });
      

      【讨论】:

      • 这里的资源是什么?
      猜你喜欢
      • 2020-07-13
      • 2019-01-29
      • 2021-11-26
      • 2017-03-06
      • 2018-07-20
      • 1970-01-01
      • 2019-09-03
      • 2022-06-12
      • 2014-11-19
      相关资源
      最近更新 更多