为什么React fetch()向服务器发送2个请求?

时间:2018-09-29 08:08:00

标签: ajax reactjs 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);
      });

当我在Chrome中打开网络日志时,会看到以下内容: screenshot

那么为什么有2个请求而不是1个?它们都在服务器端被接受。

此请求由onClick事件处理:

<div className="btn" onClick={this.handleSubmit} /></div>

问题是,这是一个POST请求,我需要在其中获取数据,因此一个请求(如果它发送了标头以检查交叉源),将在服务器上引发错误。

组件代码非常庞大,因此我将其表示为:

<StyledDiv>
  <FormControl>...</FormControl>
  <FormControl>...</FormControl>
  <FormControl>...</FormControl>
  <FormControl>...</FormControl>
  <div className="btn" onClick={this.handleSubmit} /></div>
</StyiledDiv>

2 个答案:

答案 0 :(得分:1)

我不知道为什么这是我自己发生的。

出于安全原因,我抬起头来,发现了关于preflighted requests的内容。

fetch首先将检查Web API,以查看使用OPTION动词发送是否安全,如果可以,它将使用您指定的动词POST再次发送请求。情况。

enter image description here

因此,该问题似乎与fetch如何处理CORS有关。

答案 1 :(得分:0)

尝试使用,

“内容类型”:“ application / x-www-form-urlencoded” 代替 “ Content-Type”:“ application / json”

它将发送一个呼叫,而不发送选项呼叫