Headers not found

Hello,

I’m working on a project that will send request to an API. I use for that the “fetch” JS function with some Headers.

My problem is the following : Glitch is telling me that he does not found the Headers function. Here’s the code :

  function catchURI() {
  var URI = "";
  method: "GET";
  var recherche = "ava max salt";
  var search = "https://api.spotify.com/v1/search";
  var myHeaders = new Headers({
    q: catchURI.recherche,
    type: "track",
    market: "CH",
    limit: "1",
    Authorization: process.env.SPOTIFY_TOKEN
  });

  var myInit = { method: "GET", headers: myHeaders, cache: "default" };

  fetch(search, myInit)
    .then(function(response) {
      return response.json;
    })
    .then(function(json) {
      URI = json.data[0].uri;
    });
} 

What can I do for this ? Should I install something ?

Best regards.

I’m not a Node expert but I do use JS quite a bit and I’m pretty sure the Fetch API (of which the Headers interface is apart of) is implemented by the browser’s window object, so it wouldn’t be available in Node.

A quick Google search pulled up this article which I think will solve your issue by replacing fetch with something supported by Node:

@FlantasticDan (and @LeRouteur) , the Fetch API is available on Node.js, except that you need to install the node-fetch npm package.

npm install node-fetch

Then at the top of your code:

var fetch = require('node-fetch');

fetch('url-here')...
// and do the fetch like usual

I’m a bit confused on whether you are using Node.js or not, so I’ll tell you few problems with your code, depending on if you’re using Node.js or not:

If you’re using Node.js

If you’re using Node.js, then your code should work, after you have done the instructions in the above post.

If you’re not using Node.js

If you’re not using Node.js, your code will work and you don’t need to do whatever I have said in the above post, but your authorization won’t work because you’re using process.env.SPOTIFY_TOKEN. Note that .env (referred to using process.env) variables are only available on Node.js (server-side) and not the browser (client-side).

Hey, thank’s for the answers.

I did what you mentionned, and nothing changed. I still get the following error :

ReferenceError: Headers is not defined.

I also tried to put his code to a computer running Node and editing it with VSCode, but it still does not work.

What is going on ?

Best regards.

EDIT : I changed the type of request, since it’s a coding request, not only a Glitch issue.