What is the best way to add a "x-api-key" header to a get request in NodeJS + Express?

9.7k views Asked by At

I want to send a get request but I need to insert my api key in to a 'x-api-key' header. I am using NodeJS + Express. Right now i'm using fetch from the "isomorphic unfetch" lib:

https://github.com/developit/unfetch/tree/master/packages/isomorphic-unfetch

I use it in order to fetch data from the get request. I use this library specially because it works well on both the server and a client.

How should I add the header to my request? Thanks!

1

There are 1 answers

0
V. Dimitrov On

There's an example in the unfetch repository that shows how to add headers to fetch requests.

// complex POST request with JSON, headers:
fetch('/bear', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': 'Bearer XYZ'
  },
  body: JSON.stringify({ hungry: true })
}).then( r => {
  open(r.headers.get('location'));
  return r.json();
})