Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does React fetch() send 2 requests to the server?

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: screenshot

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>
like image 800
Zoltan Avatar asked Nov 08 '22 01:11

Zoltan


1 Answers

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.

enter image description here

So the issue seems to be specific to how fetch handles CORS.

like image 185
dance2die Avatar answered Nov 14 '22 21:11

dance2die