正在从节点获取响应文本



我对节点获取还很陌生,我正在做一个简单的get请求,以获取我的邮递员收藏列表。我可以获得响应文本并在控制台中将其记录在函数中但是当我将responseText返回到一个变量并将其记录时,我得到了一个空结果,有人能告诉我为什么吗?

const fetch = require("node-fetch");
async function getCollections() {
var myHeaders = new fetch.Headers();
myHeaders.append(
"X-Api-Key",
"<API-KEY>"
);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
url = "https://api.getpostman.com/collections";
const requestResponse = await fetch(url, requestOptions);
const response = await requestResponse.text();
return response;
}
const result = getCollections();
console.log(result);

在异步函数有机会返回解析的promise之前,您似乎正在记录result。我可以想出两种方法来解决这个问题:

const fetch = require("node-fetch");
async function getCollections() {
var myHeaders = new fetch.Headers();
myHeaders.append(
"X-Api-Key",
"<API-KEY>"
);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
url = "https://api.getpostman.com/collections";
const requestResponse = await fetch(url, requestOptions);
const response = await requestResponse.text();
return response;
}
getCollections().then(console.log);

或者在异步函数中移动控制台日志。

const fetch = require("node-fetch");
async function getCollections() {
var myHeaders = new fetch.Headers();
myHeaders.append(
"X-Api-Key",
"<API-KEY>"
);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
url = "https://api.getpostman.com/collections";
const requestResponse = await fetch(url, requestOptions);
const response = await requestResponse.text();
console.log(response)
return response;
}
getCollections()

相关内容

  • 没有找到相关文章

最新更新