2

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

2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - I did not notice I'd copied my code into the wrong line. thanks for the code review!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.