Reputation: 109
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?
Upvotes: 1
Views: 10166
Reputation: 2137
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))
Upvotes: 1