Using the Fetch API with API key header - javascript

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?

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))

Related

Accessing in Chrome POST response body from Cloudflare Worker

I am trying to read a response from a Cloudflare Worker API, I have not set anything sepcial about it and in Postman the request works as expected. I am guessing I am missing some header but I am not sure which one or even if that is the reason reading the reponses body is not working in browser.
This is how I fetch the data:
const url = `${process.env.SOME_URL}/v1/method?token=${TOKEN}`
const headers = new Headers();
headers.append("Content-Type", "application/json;charset=UTF-8");
const requestOptions = {
method: 'POST',
redirect: 'follow',
mode: 'no-cors',
body: JSON.stringify(body),
headers
// referrerPolicy: 'no-referrer',
};
return fetch(url, requestOptions)
.then(async (response) => {
// no body to be parsed
return response.json()
} )
.then(result => console.log(result))
.catch(error => console.log('error', error));
Looking forward to your answers, thank you.
This behaviour is due to the no-cors config of the fetch-api.
For more details read about opaque requests here:
What limitations apply to opaque responses?

Discord api get guild

I'm trying to fetch my guild info from discord API
fetch('https://discord.com/api/guilds/772037458996101140', {
headers: {
authorization: 'bot Nzc******zNjYzOTAz.GPwhCV.rhIcH****5R8ZS-cIo4MjPcBVxO6wYsUXhY'
},
})
.then(result => result.json())
.then(response => {
console.log(response);
})
.catch(console.error)
only reciving 401 (unauthorized)
i tried changing "bot" to "BOT", "Bot", "Bearer"
and doing authorization using access token from Oauth2
The problem lies in how the Authorization header has been specified. The correct way specify headers would be:
fetch('https://discord.com/api/guilds/772037458996101140', {
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': 'bot Nzc******zNjYzOTAz.GPwhCV.rhIcH****5R8ZS-cIo4MjPcBVxO6wYsUXhY',
},
})
.then(result => result.json())
.then(response => {
console.log(response);
})
.catch(console.error)
Hope this helps.
Edit
Also added crendentials and withCredentials based on this answer.
I was sending http request from front-end and when i moved it to back-end or just used python test file it worked using : Authorization: 'Bot <TOKEN>'
not sure why but it works how it should mby somebody can explain ?

How do you make an API request using browser fetch with token auth

I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
You are not sending headers properly.
Try this.
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
and then
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})

JS Fetch takes only OPTIONS request and print that out

Im trying to make a request from my React App to my backend server, the frontend do a OPTIONS request and that is OK, the problem is that my then on the fetch console logs the OPTIONS response, and not the real response that is made efter the OPTIONS request.
fetch('http://localhost:8080/api/kp/ticket', {
headers: {
"token": sessionStorage.getItem('token')
},
mode: 'cors',
method: 'GET'
}).then(data => console.log(data));
try this
fetch('http://localhost:8080/api/kp/ticket', {
headers: {
"token": sessionStorage.getItem('token')
},
mode: 'cors',
method: 'GET'
}).then(data => (data.json())
.then(res => console.log(res));
Check in "Other" tab in chrome devtools. Not in XHR

issue with reading result from POST in fetch request to Github API

I am using the fetch api to get an access token returned from the github api.
When I check the network tab I see that the token is returned but I am unable to access it in my fetch request.
My code looks like this:
fetch(`https://github.com/login/oauth/access_token?client_id=***&client_secret=***&code=${code}&redirect_uri=http://localhost:3000/&state=react`, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(function(res) {
console.log(res); // I have already tried return res.json() here
})
The console displays the following error if I return res.json():
index.js:30 Uncaught (in promise) SyntaxError: Unexpected end of input
The GitHub docs states the response takes the following format:
By default, the response takes the following form:
access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer
I guess it isn't returning valid json but just a string so I am not sure how to access this response.
The response looks like this:
However, when I try and log out the response I get SyntaxError: Unexpected end of input
If you are using mode: 'no-cors, browser will restrict to access body. Browser has security for cross domain. If you want to access body you have to call without mode: 'no-cors property.
https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
This will work
fetch(`https://jsonplaceholder.typicode.com/posts/1`, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(res => res.json())
.then(function(res) {
console.log(res);
})
This will not work
fetch(`https://jsonplaceholder.typicode.com/posts/1`, {
method: 'GET',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(res => res.json())
.then(function(res) {
console.log(res);
})
I think you're almost there. You've mentioned this link to the docs. If you read further, you can see that to get response in JSON, you need to include a header named Accept with the value of application/json.
fetch(` ... `, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json'
})
}).then(function(res) {
...
})
This way, you can apply .json() on res.

Categories

Resources