frburton
frburton

Reputation: 47

Headers is not defined in fetch call

Tried making a fetch call to a URL to an API that requires basic authentication. I found a question that uses bases-64 module to encode the URL headers and put them in the fetch call. 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?

Upvotes: 2

Views: 8869

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20924

The Headers constructor does not exist in the node.js context. Like fetch you'll need to include it from the node-fetch package. You can use a destructuring assignment to get it from the 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();

Alternatively use modules with the import syntax. This enables you to import both in a single line.

import fetch, { Headers } from 'node-fetch';

See the documentation of node-fetch for more details.

Upvotes: 5

Related Questions