為什么React fetch()向服務器發送2個請求?

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


I am trying to send an AJAX request to the server via fetch():

我試圖通過fetch()向服務器發送一個AJAX請求:

    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

當我在Chrome中打開網絡日志時,我看到如下內容:

So why are there 2 requests instead of 1? They are both accepted on the server side.

那么為什么有2個請求而不是1個?它們都在服務器端被接受。

This request is handled by an onClick event:

此請求由onClick事件處理:

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

問題是,這是一個POST請求,我需要在其中獲取數據,因此一個請求(如果它發送標頭以檢查交叉原點),則在服務器上啟動錯誤。

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>

1 个解决方案

#1


1  

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.

fetch將首先檢查Web API以查看使用OPTION動詞發送是否安全,當它正常時,它會使用您指定的動詞POST再次發送請求。

enter image description here

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

所以問題似乎特定於fetch如何處理CORS。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2018/09/29/7251d6cd2d97f88f1487dfea61970b0f.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com