在OPTIONS响应后使Fetch API与CORS一起使用 [英] Making fetch API work with CORS after OPTIONS response

查看:114
本文介绍了在OPTIONS响应后使Fetch API与CORS一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我们的API中获取数据。该API已启用CORS支持并返回以下对OPTIONS请求的响应:

I are trying to fetch data from our API. The API has enabled CORS support and returns the below response to the OPTIONS request:

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

API不允许内容类型 'application / json'以外的任何内容。

The API doesn't allow 'Content-type' anything other than 'application/json'.

使用此限制,我试图使用React-Native的 fetch 方法获取数据。

Using this limitation, I am trying to use the fetch method of React-Native to get the data.

方法1(无费用):

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

使用此方法,浏览器会自动将内容类型发送为文本/纯文本 '。我认为这是因为CORS默认情况下只允许三个标头之一。但是,由于服务器不支持此内容类型,因此它将返回不支持的内容类型的错误。

With this method, the browser automatically sends the content-type as 'text/plain'. I assume this is because CORS allow just one of the three headers by default. However, since the server doesn't support this content-type, it returns an error back for unsupported content type.

方法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 选项。为此,服务器使用空对象以及上述标头集进行答复。下一个调用是实际的POST API调用,服务器将使用包含某些数据的适当JSON响应来响应该调用。但是,通过我的代码进入控制台的响应是 {} 。我认为这是因为react的 fetch API返回了 OPTIONS 调用的响应,而不是实际的 POST 调用。

In this scenario, using Chrome's F12 network tool, I can see the server returning data : the first request to the server is a fetch for OPTIONS. To this, the server replies back with an empty object along with the above headers set. The next call is the actual POST API call, to which the server responds back with a proper JSON response containing some data. However, the response which is getting on the console via my code is {}. I assume this is because the react's fetch API is returning back the response of the OPTIONS call instead of the actual POST call.

是否有任何方法可以忽略OPTIONS请求的响应并获取 then 方法来处理

Is there any way to ignore the response of the OPTIONS request and get the then method to process the response of the subsequent request?

推荐答案

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

The immediate problem you’re hitting is that your code as currently written expects the response to be JSON but the response is actually a Promise that you need to handle in order to get the JSON.

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

So you need to instead do something like this:

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

这篇关于在OPTIONS响应后使Fetch API与CORS一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆