Javascript 访问控制源头错误在 React Web 中使用 Axios 在 Chrome 中抛出错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45975135/
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
Access Control Origin Header error using Axios in React Web throwing error in Chrome
提问by SeaWarrior404
Im making an API call using Axios in a React Web app. However Im getting the error in Chrome as,
我在 React Web 应用程序中使用 Axios 进行 API 调用。但是我在 Chrome 中收到错误消息,
XMLHttpRequest cannot load https://example.restdb.io/rest/mock-data. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
XMLHttpRequest 无法加载https://example.restdb.io/rest/mock-data。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost:8080'。
{
axios.get('https://example.restdb.io/rest/mock-data', {
headers: {
'x-apikey': 'API_KEY',
},
responseType: 'json',
}).then(response => {
this.setState({ tableData: response.data });
});
}
I have also read several answers on StackOverflow about the same issue, titled "Access-Control-Allow-Origin" but still coudnt figure out how to solve this. I dont want to use an extension IN Chrome or use a temporary hack to solve this. Please suggest the standard way of solving the above issue.
我还在 StackOverflow 上阅读了几个关于同一问题的答案,标题为“Access-Control-Allow-Origin”,但仍然不知道如何解决这个问题。我不想在 Chrome 中使用扩展程序或使用临时黑客来解决这个问题。请提出解决上述问题的标准方法。
After trying out few answers I have tried with this,
在尝试了几个答案之后,我已经尝试过这个,
headers: {
'x-apikey': '59a7ad19f5a9fa0808f11931',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},
Now I get the error as,
现在我得到的错误是,
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response
预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Access-Control-Allow-Origin
采纳答案by Vlad Povalii
If your backend support CORS, you probably need to add to your request this header:
如果您的后端支持 CORS,您可能需要在请求中添加以下标头:
headers: {"Access-Control-Allow-Origin": "*"}
[Update] Access-Control-Allow-Originis a response header - so in order to enable CORS - you need to add this header to the response from your server.
[更新] Access-Control-Allow-Origin是一个响应标头 - 因此为了启用 CORS - 您需要将此标头添加到来自您的服务器的响应中。
But for the most cases better solution would be configuring the reverse proxy, so that your server would be able to redirect requests from the frontend to backend, without enabling CORS.
但在大多数情况下,更好的解决方案是配置反向代理,以便您的服务器能够将请求从前端重定向到后端,而无需启用 CORS。
You can find documentation about CORS mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
您可以在此处找到有关 CORS 机制的文档:https: //developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
回答by AMDP
!!!
I had a similar problem and I found that in my case the withCredentials: truein the request was activating the CORS check while issuing the same in the header would avoid the check:
!!!我有一个类似的问题,我发现在我的情况下withCredentials: true,请求正在激活 CORS 检查,同时在标头中发出相同的内容将避免检查:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMIssingAllowCredentials
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMIssingAllowCredentials
do not use
withCredentials: truebut set
'Access-Control-Allow-Credentials':truein the headers
不使用
withCredentials: true但'Access-Control-Allow-Credentials':true在标题中设置
回答by Chuck-Durst
Using the Access-Control-Allow-Origin header to the request won't help you in that case while this header can only be used on the response...
在这种情况下,对请求使用 Access-Control-Allow-Origin 标头将无济于事,而此标头只能用于响应...
To make it work you should probably add this header to your response.You can also try to add the header crossorigin:trueto your request.
为了使它工作,您可能应该将此标头添加到您的响应中。您也可以尝试将标头添加crossorigin:true到您的请求中。
回答by LvDevR1
As I understand the problem is that request is sent from localhost:3000 to localhost:8080 and browser rejects such requests as CORS. So solution was to create proxy
据我了解,问题是请求从 localhost:3000 发送到 localhost:8080 并且浏览器拒绝了 CORS 等请求。所以解决方案是创建代理
My solution was :
我的解决方案是:
import proxy from 'http-proxy-middleware'
app.use('/api/**', proxy({ target: "http://localhost:8080" }));
回答by Parthasarathy S
In node js(backend), add these lines to support Access-Control-Allow-Origin,
在节点 js(backend) 中,添加这些行以支持 Access-Control-Allow-Origin,
const express = require('express')
const app = express()
app.use(cors())
回答by Vakhtang Elisabedashvili
$ npm install cors
After installing cors from npm add the code below to your node app file. It solved my problem.
从 npm 安装 cors 后,将以下代码添加到您的节点应用程序文件中。它解决了我的问题。
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
回答by Cybersupernova
First of all, CORS is definitely a server-side problem and not client-side but I was more than sure that server code was correct in my case since other apps were working using the same server on different domains. The solution for this described in more details in other answers.
首先,CORS 绝对是服务器端问题,而不是客户端问题,但我非常确定服务器代码在我的情况下是正确的,因为其他应用程序在不同域上使用相同的服务器工作。其他答案中更详细地描述了此解决方案。
My problem started when I started using axioswith my custom instance. In my case, it was a very specific problem when we use a baseURL in axiosinstance and then try to make GETor POSTcalls from anywhere, axios adds a slash / between baseURL and request URL. This makes sense too, but it was the hidden problem. My Laravel server was redirecting to remove the trailing slash which was causing this problem.
当我开始使用axios我的自定义实例时,我的问题就开始了。就我而言,当我们在axios实例中使用 baseURL然后尝试从任何地方发出GET或POST调用时,这是一个非常具体的问题,axios 在 baseURL 和请求 URL 之间添加了一个斜杠 / 。这也有道理,但这是隐藏的问题。我的 Laravel 服务器正在重定向以删除导致此问题的尾部斜杠。
In general, the pre-flight OPTIONSrequest doesn't like redirects. If your server is redirecting with 301 status code, it might be cached at different levels. So, definitely check for that and avoid it.
通常,飞行前OPTIONS请求不喜欢重定向。如果您的服务器使用 301 状态代码重定向,则它可能会在不同级别缓存。所以,一定要检查并避免它。
回答by klimqx
I had the same error. I solved it by installing CORS in my backend using npm i cors. You'll then need to add this to your code:
我有同样的错误。我通过使用npm i cors. 然后,您需要将其添加到您的代码中:
const cors = require('cors');
app.use(cors());
This fixed it for me; now I can post my forms using AJAX and without needing to add any customized headers.
这为我修复了它;现在我可以使用 AJAX 发布我的表单,而无需添加任何自定义标题。
回答by Alfred Skaria
I had a similar problem when I tried to create the React Axios instance.
我在尝试创建 React Axios 实例时遇到了类似的问题。
I resolved it using the below approach.
我使用以下方法解决了它。
const instance = axios.create({
baseURL: "https://jsonplaceholder.typicode.com/",
withCredentials: false,
headers: {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
}
});
回答by Dinesh Naik
}, "proxy": "http://localhost:8080", "devDependencies": {
}, "proxy": " http://localhost:8080", "devDependencies": {
use proxy in package.json
在 package.json 中使用代理

