如何在Node.js中执行我们的代码之前等待一个HTTP请求



我试图使一个API的GET请求,并希望存储它在另一个变量返回的数据但是Javascript不会等待请求完成并将变量记录为Undefined

app.get("/", function (req, res) {
const url = "https://animechan.vercel.app/api/random";
let str = "";
let quote;

https.get(url,(resposne)=>{
resposne.on("data",(data)=>{
str+=data;
});
resposne.on("end",()=>{
const info=JSON.parse(str);
quote=info.quote;
});
});
console.log(quote);
res.render("header", {
quote: quote
});
});

我很高兴如果有人能告诉我如何解决这个问题,我在哪里可以学习更多,因为我是一个初学者的javascript。

快速回答是,您需要将该代码放在response.on('end')回调中。

resposne.on("end",()=>{
const info=JSON.parse(str);
quote=info.quote;
// now we can use res.render
console.log(quote);
res.render("header", {
quote: quote
});
});

然而,遵循这种方法将导致回调地狱,不可读和不可扩展的项目代码。理想情况下,你应该开始使用承诺。承诺是javascript的一个重要组成部分,是开发人员必须掌握的知识。

另外,我想指出的是,你不需要从头开始实现http调用功能,也不需要尝试将这样的代码包装到promise中。相反,最好使用fetch api(如果您使用的是node版本18或更高)或使用相应的库,例如node-fetch。

在之后调用res.sendHTTP调用完成

app.get("/", function (req, res) {
const url = "https://animechan.vercel.app/api/random";
let str = "";
let quote;

https.get(url,(resposne)=>{
resposne.on("data",(data)=>{
str+=data;
});
resposne.on("end",()=>{
const info=JSON.parse(str);
quote=info.quote;
// Send response _after_ the http call is complete
console.log(quote);
res.render("header", {
quote: quote
});
});
});
});

我建议使用node的fetch,因为默认的HTTP客户端有点不符合人体工程学

获取API引用:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Node.js API参考:https://nodejs.org/dist/latest-v18.x/docs/api/globals.html#fetch

最新更新