I am trying to send an AJAX request to the server via fetch()
:
fetch('/api/addUserObject', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({...this.state, token: this.props.userData.token,
profile: this.props.currentProfile }),
}).then(response => response.json())
.then(data => {
console.log(data);
});
When I open the network log in Chrome I see something like this:
So why are there 2 requests instead of 1? They are both accepted on the server side.
This request is handled by an onClick event:
<div className="btn" onClick={this.handleSubmit} /></div>
The problem is, that this is a POST request and I need to get data in this, so one request (if it sends headers to check for cross origin), initiates an error on the server.
The component code is massive, so I will represent it as:
<StyledDiv>
<FormControl>...</FormControl>
<FormControl>...</FormControl>
<FormControl>...</FormControl>
<FormControl>...</FormControl>
<div className="btn" onClick={this.handleSubmit} /></div>
</StyiledDiv>
I wasn't aware of why this was happening myself.
I looked up a bit and found out about preflighted requests for a security reasons.
fetch
will first check the Web API to see if it's safe to send using OPTION
verb and when it's fine, it sends the request again using your specified verb, POST
in your case.
So the issue seems to be specific to how fetch
handles CORS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With