node.js - 如何使用 Node Fetch 将来自 HTTP 请求的数据保存在变量中?

标签 node.js rest httprequest node-fetch

我尝试使用 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);

结果 ==> 未定义

有人可以帮助我!

最佳答案

您的 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);

关于node.js - 如何使用 Node Fetch 将来自 HTTP 请求的数据保存在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68033609/

相关文章:

node.js - `npm list -g` 未列出任何模块

git - REST-完全访问 : Cannot add file to repository in Gitlab

java - 使用 spring 框架将 Java 对象中的顺序保存为 json

c# - 在 C# 中使用带有 API key 的 HttpClient 类的 PostAsync 方法

go - 我应该在包级别但在 http 处理程序之外声明变量吗?

javascript - UglifyJS 抛出错误 Unexpected token : operator (>)

javascript - 如何等待多个 fs.readFile 调用?

java - 如何访问从android中的restful web服务传递的json数组?

java - fater网页源提供者

node.js - 在 Node 中使用 zone.js 钩子(Hook)