在 OPTIONS 响应后使 fetch API 与 CORS 一起工作

Making fetch API work with CORS after OPTIONS response

我正在尝试从我们的 API 中获取数据。 API 启用了 CORS 支持和 returns 以下对 OPTIONS 请求的响应:

Access-Control-Request-Headers:content-type  
Access-Control-Allow-Origin:*  

API 不允许 'Content-type''application/json' 之外的任何其他内容。

利用这个限制,我尝试使用React-Native的fetch方法来获取数据。

方法一(no-cors):

{
    method: 'POST',
    mode: "no-cors",
    headers: {
       'content-type': 'application/json'
}

使用此方法,浏览器会自动将 content-type 发送为 'text/plain'。我认为这是因为 CORS 默认只允许三个 headers 之一。但是,由于服务器不支持此 content-type,它 returns 返回不支持的内容类型的错误。

方法 2(有 cors 或没有):

{ 
    method: 'POST',
    mode: "cors", // or without this line
    redirect: 'follow',
    headers: {
        'content-type': 'application/json'
    }
}   
...   
.then(response => console.log(response))

在这种情况下,使用 Chrome 的 F12 网络工具,我可以看到服务器返回数据:对服务器的第一个请求是 fetch for OPTIONS。为此,服务器回复一个空的 object 以及上面的 headers 集。下一个调用是实际的 POST API 调用,服务器以包含一些数据的正确 JSON 响应响应。但是,通过我的代码在控制台上获得的响应是​​ {}。我假设这是因为反应的 fetch API 正在返回 OPTIONS 调用的响应而不是实际的 POST 调用。

有没有什么办法可以忽略OPTIONS请求的响应,得到then方法来处理后续请求的响应?

您遇到的直接问题是,您当前编写的代码期望响应为 JSON,但响应实际上是您需要处理以获得 JSON 的 Promise。

因此您需要改为执行以下操作:

fetch("https://example.com")
    .then(response => response.json())
    .then(jsondata => console.log(jsondata))