【问题标题】:Headers is not defined in fetch call获取调用中未定义标头
【发布时间】:2021-04-22 06:19:19
【问题描述】:

尝试对需要基本身份验证的 API 的 URL 进行 fetch 调用。我找到了一个question,它使用 bases-64 模块对 URL 标头进行编码并将它们放入 fetch 调用中。尝试了变化,但它不起作用。

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

错误:

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)

我做错了什么?

【问题讨论】:

  • 使用let headers = new fetch.Headers() 或要求Headersconst Headers = require("node-fetch").Headersconst { Headers } = require("node-fetch"); 分开使用

标签: javascript http fetch


【解决方案1】:

Headers 构造函数在 node.js 上下文中不存在。像fetch 一样,您需要从node-fetch 包中包含它。您可以使用解构赋值从fetch 函数中获取它。

const fetch = require('node-fetch');
const { Headers } = fetch;

或者直接使用属性创建一个新实例。

let headers = new fetch.Headers();

更多详情请见the documentation of node-fetch

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 2017-01-22
    • 2014-04-22
    相关资源
    最近更新 更多