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

Zol*_*tan 5 ajax fetch reactjs

我正在尝试通过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);
      });
Run Code Online (Sandbox Code Playgroud)

当我在 Chrome 中打开网络日志时,我看到如下内容: 截屏

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

此请求由 onClick 事件处理:

<div className="btn" onClick={this.handleSubmit} /></div>
Run Code Online (Sandbox Code Playgroud)

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

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

<StyledDiv>
  <FormControl>...</FormControl>
  <FormControl>...</FormControl>
  <FormControl>...</FormControl>
  <FormControl>...</FormControl>
  <div className="btn" onClick={this.handleSubmit} /></div>
</StyiledDiv>
Run Code Online (Sandbox Code Playgroud)

dan*_*die 2

我自己也不知道为什么会发生这种情况。

我查了一下,发现出于安全原因有 预检请求。

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

在此输入图像描述

所以这个问题似乎特定于如何fetch处理CORS