Javascript 在 fetch api 中启用 CORS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51017702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:44:00  来源:igfitidea点击:

Enable CORS in fetch api

javascriptreactjsfetch-api

提问by johntanquinco

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

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

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

无法加载https://site/data.json:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost:8080'。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。localhost/:1 Uncaught (in promise) TypeError: Failed to fetch

I am trying to enable CORSin 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.

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

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

回答by Kishan Mundha

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

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

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.

您可以使用mode: 'cors'. 在这种情况下,浏览器不会抛出跨域执行,但浏览器不会在您的 javascript 函数中给出响应。

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

因此,在这两种情况下,您都需要cors在服务器中进行配置,或者需要使用自定义代理服务器。