fetch doesn't set headers in chrome - javascript

I try to get a POST request working via the fetch() function. The problem is that my headers won't be set and the request fails.
Here is an example code of my request:
fetch('https://google.com', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-FOO-BAR': 'bla'
},
mode: "no-cors",
body: JSON.stringify({
data: "here"
})
});
My main problem is, that the Content-Type will be set to text/plain, which is why my request fails. I added the X-FOO-BAR header just to see if it gets set. But it won't get set.

Related

Send a message in discord channel with POST request with undici

I'm trying to understand how the Discord API works, and I'm struggling to send a message in a channel. the code executes fine, but the message is not being sent. I tried with this code:
await request(`https://discord.com/api/v9/channels/${channel_id}/messages`, {
method: "POST",
body: content,
headers: this.headers,
});
but it doesn't work. What am i doing wrong?
content is the string I want to send, it's a function parameter and so is channel_id.
headers is:
{
authorization: `Bot ${token}`,
accept: "*/*",
};
The request returns a status code of 400 (Bad request).
I solved it. The issue is that I didn't specify the Content-Type of the request, and passed the content as a string. I added to the headers: "content-type": "application/json", and to the body I passed a Json object of the content:
await request(`https://discord.com/api/v9/channels/${channel_id}/messages`, {
method: "POST",
headers: this.headers,
body: json({ content }),
});
And the headers:
this.headers = {
authorization: `Bot ${token}`,
"content-type": "application/json",
};

Content-type from fetch in locally run React code

I am new to front end dev. How can I set "application/json" content-type and gzip content-encoding in the fetch call in locally run React code?
const data = await fetch(url, {
method: 'post',
body: body,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json' // this does not work when run locally
}
});
You could try this
const data = await fetch(url, {
method: 'post',
body: JSON.stringify(body), // this will encode body to string, assuming it's an Object
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
but I'm not sure what do you want with "gzip content-encoding". If the console prints any errors, they can be helpful too

Different headers for post and get request with axios,create?

export default myAPI = axios.create({
baseURL: 'myapiurl',
// headers for post reuqest
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
'X-CSRF-TOKEN': 'o987WyyzM7ktyEVzP4dakCdIY12LprtJU8qZHs5Xs0s',
},
// headers for get requests
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
Basically want conditional headers depending on weather a post or a get request is being made.
You can use different headers based on HTTP method in this way:
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
As explained here: https://github.com/axios/axios#global-axios-defaults

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.

Fetch response malformed

The issue is basically that the fetch response object is not correct. Pictures to clarify the issue are below as it is hard to explain.
My fetch request code.
fetch(this.constructUrl(url), {
method: method,
mode: 'no-cors',
headers: new Headers({
'Authorization': 'Bearer ' + this.token,
'Accept': 'application/json',
'Content-Type': 'application/json',
}),
body: new FormData(document.getElementById(formIdentifier))
}).then(function (response) {
if (response.ok) {
return response.json().then(callback);
}
console.log(response);
}).catch(function(error) {
console.log(error);
});
The fetch response object.
The chrome response/request details
The chrome response data
So as you can see, the data in chrome looks correct but for some reason, the fetch response object does not seem to reflect what chrome picks up.
I had to switch 'no-cors' to 'cors' and allow cors in my rest stack.

Categories

Resources