1

How do we configure the Fetch API to include the API key header?

I've created an API that I can successfully receive responses from POSTMAN or Fiddler by including the API key in the headers.

However, from my code (React / Javavascript) using the following snippet fails;

        return fetch(url)
      .then(response => response.json(),{
        mode: 'cors', 
        headers: {
          'x-api-key': '5485748746547e847483983343433243',
          'User-Agent' : 'My-App',
          'Accept': '*/*',
        },
      })
      .catch(error => console.log('Error while fetching:', error))

In Postman I can remove all the headers except the x-api-key and it works fine. No combination of headers or configuration seems to work in my code.

If I capture the request in Fiddler, the x-api-key header has not been added by the Fetch request.

What is the correct way to configure fetch to send the api key header?

1 Answer 1

1

Your options are in the wrong place. They should be in the 2nd parameter of the fetch function.

return fetch(url, {
    mode: 'cors', 
    headers: {
      'x-api-key': '5485748746547e847483983343433243',
      'User-Agent' : 'My-App',
      'Accept': '*/*',
    },
  })
  .then(response => response.json())
  .catch(error => console.log('Error while fetching:', error))
1
  • Thanks - I did not notice I'd copied my code into the wrong line. thanks for the code review!
    – djnz
    Commented May 11, 2021 at 8:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.