在fetch api中启用CORS [英] Enable CORS in fetch api

查看:94
本文介绍了在fetch api中启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误消息,无法继续

I am getting the following error message that unable me to continue


无法加载 https://site/data.json :对预检请求的响应
未通过访问控制检查:否'访问控制 - 允许 - 来源'
标头出现在请求的资源上。因此不允许访问来源
' http:// localhost:8080 '。如果不透明的
响应满足您的需求,请将请求的模式设置为'no-cors'到
获取禁用CORS的资源。
localhost /:1未捕获(承诺)TypeError:无法获取

Failed to load https://site/data.json: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. localhost/:1 Uncaught (in promise) TypeError: Failed to fetch

我正在尝试启用 CORS 在我的react js文件中但是我无法获得预期的结果。我已经安装了chrome扩展程序,它可以工作。但是要在生产站点中使用它,我需要在我的代码中启用它。我应该如何正确安排代码以启用 CORS

I am trying to enable CORS in my react js file but I was not able to get the expected result. I have installed a chrome extension and it work. But to use this in production site, I need to enable it inside my code. How should I properly arrange the code to enable the CORS.

fetch(URL, {
  mode: 'cors',
  headers: {
    'Access-Control-Allow-Origin':'*'
  }
})
  .then(response => response.json())
  .then(data => {


推荐答案

浏览器在客户端具有跨域安全性,用于验证服务器是否允许从您的域中获取数据。如果 Access-Control-Allow- Origin 在响应头中不可用,浏览器不允许在JavaScript代码中使用响应并在网络级别抛出异常。您需要在您的网络级别配置 cors 服务器端。

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

您可以使用模式获取请求:'cors'。在这种情况下,浏览器不会抛出execption对于跨域,但浏览器不会在你的javascript函数中给出响应。

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

所以在这两种情况下你需要配置 cors 在您的服务器中或您需要使用自定义代理服务器。

So in both condition you need to configure cors in your server or you need to use custom proxy server.

这篇关于在fetch api中启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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