【问题标题】:How to save data in variable from HTTP request using Node Fetch?如何使用 Node Fetch 将来自 HTTP 请求的数据保存在变量中?
【发布时间】:2021-09-03 02:23:34
【问题描述】:

我正在尝试使用 node-fetch 将 GET 请求中的数据保存到变量中,但我得到了一些结果! 当我控制台记录响应时,我可以看到它。但是当我将 resData 分配给变量时,我得到了未定义。

const fetch = require('node-fetch');

async function fetchData(){
const response = await fetch(url, options)
const resData = await response.json();
console.log(resData);
return resData; 
 };
 
let myApps
 
fetchData((data)=>{
 myApps = data;
});
 
console.log(myApps);

结果 ==> 未定义

有人可以帮助我!

【问题讨论】:

  • const myApps = await fetchData(); 记得在异步方法中执行它以及使用await
  • fetchData 正在异步执行,并且您的分配 myApps = data;在返回结果之前执行语句。你也需要在这里使用 await

标签: node.js rest httprequest node-fetch


【解决方案1】:

您的console.log 在您的网络请求完成之前执行。这是因为 HTTP 请求是异步的。 fetchData 方法返回 Promise。正确的实现应该是这样的:

const fetch = require('node-fetch');

async function fetchData(){
     const response = await fetch(url, options)
     const resData = response.json();
     console.log(resData);
     return resData; 
};
 
let myApps

fetchData().then((data) => {
   // the network request is completed
   myApps = data;
   console.log(myApps);
}).catch((e) => {
   // Network request has failed
   console.log(e);
});

// or using await if your parent method is an `async` function
try {
   myApps = await fetchData()
} catch (e) {
   // Network request has failed
   console.log(e);
}

更新:OP评论后

使用 express 在 API 调用中发送 fetchData 的响应

async function getData(req, res) {
  try {
     const data = await fetchData();
     // you can loop on your data as well
     
     // send the response
     res.json({ data });
  } catch (e) {
     res.status(503).json({ msg: "Internal Server Error" });
  }
}

// somewhere in your route
app.get("/data", getData);

【讨论】:

  • 感谢您的回复。问题是我想将响应保存到变量中并创建一个 for 循环来获取特定数据!
  • 你想怎么调用fetchData?一旦应用程序启动?或参加任何活动?
  • 使用 express,我想从 fetchData 获取数据,然后我使用 express 进行 GET 路由,返回 fetchData 的结果。例如,来自 fetchData 的数据是应用程序列表,我想使用 express return .json() 发出 GET 请求
  • 然后在您的controller 中调用fetchData 方法。喜欢async function(req, res) { data = await fetchData() res.json({ data ); }
  • 这是我的 Linkedin 帐户 ==> linkedin.com/in/alifnaiech 所以如果我遇到困难我可以联系你
猜你喜欢
  • 2019-07-26
  • 1970-01-01
  • 2020-09-13
  • 2019-10-22
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
相关资源
最近更新 更多