[英]Headers is not defined in fetch call
Tried making a fetch call to a URL to an API that requires basic authentication.尝试对需要基本身份验证的 API 进行对 URL 的提取调用。 I found a question that uses bases-64 module to encode the URL headers and put them in the fetch call.我发现了一个问题,它使用 bases-64 模块对 URL 标头进行编码并将它们放入 fetch 调用中。 Tried variations but it doesn't work.尝试了变化,但它不起作用。
const fetch = require("node-fetch");
const base64 = require("base-64");
let url = "<URL>";
let username = "<username>";
let password = "<password>";
let headers = new Headers();
headers.set(
"Authorization",
"Basic " + base64.encode(username + ":" + password)
);
async function getCategories(url) {
fetch(url, {
method: "GET",
headers: headers,
})
.then((response) => {
return response.json;
})
.catch((err) => {
console.log(err);
});
}
getCategories(url)
.then((response) => console.log(response))
.catch((err) => console.log(err));
Error:错误:
Headers is not defined
at Object.<anonymous> (C:\Users\User\Downloads\getCategories\getCategories.js:7:15)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
What am I doing wrong?我究竟做错了什么?
The Headers
constructor does not exist in the node.js context. node.js 上下文中不存在Headers
构造函数。 Like fetch
you'll need to include it from the node-fetch
package.像fetch
一样,您需要从node-fetch
package 中包含它。 You can use a destructuring assignment to get it from the fetch
function.您可以使用解构赋值从fetch
function 中获取它。
const fetch = require('node-fetch');
const { Headers } = fetch;
Or use the property directly to create a new instance.或者直接使用该属性创建一个新实例。
let headers = new fetch.Headers();
See the documentation of node-fetch
for more details.有关更多详细信息,请参阅node-fetch
的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.