gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:29:29 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com