首页 文章

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

提问于
浏览
5

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

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

API不允许 'Content-type''application/json' 以外的任何内容 .

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

Method 1 (no-cors):

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

使用此方法,浏览器会自动将内容类型发送为“text / plain” . 我假设这是因为CORS默认只允许三个标头中的一个 . 但是,由于服务器不支持此内容类型,因此会针对不支持的内容类型返回错误 .

Method 2 (with cors or with nothing):

{ 
    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 . 为此,服务器回复一个空对象以及上面的 Headers 集 . 下一个调用是实际的POST API调用,服务器使用包含一些数据的正确JSON响应向其响应 . 但是,通过我的代码在控制台上获得的响应是 {} . 我假设这是因为react的 fetch API返回 OPTIONS 调用的响应而不是实际的 POST 调用 .

有没有办法忽略OPTIONS请求的响应并获得 then 方法来处理后续请求的响应?

1 回答

  • 11

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

    所以你需要做这样的事情:

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

相关问题