Javascript CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42061727/
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
CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
提问by Abhishek Kulshrestha
I am trying to send the request from one localhost port to the another. I am using angularjs on the frontend and node on the backend.
我正在尝试将请求从一个本地主机端口发送到另一个。我在前端使用angularjs,后端使用node。
Since it is CORSrequest, In node.js, i am using
由于是CORS请求,因此在 node.js 中,我正在使用
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
and in the angular.js service file, I am using
在 angular.js 服务文件中,我使用
return {
getValues: $resource(endpoint + '/admin/getvalues', null, {
'get': {
method: 'GET',
headers:{'Authorization':'Bearer'+' '+ $localStorage.token}
}
}),
}
I am getting the following error
我收到以下错误
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
预检响应中的 Access-Control-Allow-Headers 不允许请求头字段授权。
Please help!
请帮忙!
采纳答案by vikas
You have to add options also in allowed headers. browser sends a preflight request before original request is sent. See below
您还必须在允许的标题中添加选项。浏览器在发送原始请求之前发送预检请求。见下文
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
From source https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
从源https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The
Access-Control-Request-Methodheader notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. TheAccess-Control-Request-Headersheader notifies the server that when the actual request is sent, it will be sent with aX-PINGOTHERandContent-Typecustom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.
在 CORS 中,发送带有 OPTIONS 方法的预检请求,以便服务器可以响应是否可以使用这些参数发送请求。的
Access-Control-Request-Method报头通知的服务器作为预检请求的一部分被发送的实际请求时,它将被与POST请求方法发送。的Access-Control-Request-Headers报头通知服务器被发送的实际请求时,它将被与发送X-PINGOTHER和Content-Type自定义首部。服务器现在有机会确定在这些情况下它是否希望接受请求。
EDITED
已编辑
You can avoid this manual configuration by using npmjs.com/package/corsnpm package.I have used this method also, it is clear and easy.
您可以通过使用npmjs.com/package/corsnpm package来避免这种手动配置。我也使用过这种方法,它很简单。
回答by Hung Vu
This is an API issue, you won't get this error if using Postman/Fielder to send HTTP requests to API. In case of browsers, for security purpose, they always send OPTIONS request/preflight to API before sending the actual requests (GET/POST/PUT/DELETE). Therefore, in case, the request method is OPTION, not only you need to add "Authorization" into "Access-Control-Allow-Headers", but you need to add "OPTIONS" into "Access-Control-allow-methods" as well. This was how I fixed:
这是一个 API 问题,如果使用 Postman/Fielder 向 API 发送 HTTP 请求,您将不会收到此错误。对于浏览器,出于安全目的,它们总是在发送实际请求(GET/POST/PUT/DELETE)之前向 API 发送 OPTIONS 请求/预检。因此,如果请求方法是OPTION,不仅需要在“Access-Control-Allow-Headers”中添加“Authorization”,还需要在“Access-Control-allow-methods”中添加“OPTIONS”作为好。这就是我修复的方式:
if (context.Request.Method == "OPTIONS")
{
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept, Authorization" });
context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
}
回答by o.z
The res.header('Access-Control-Allow-Origin', '*');wouldn't work with Autorization header.
Just enable pre-flight request, using cors library:
该res.header('Access-Control-Allow-Origin', '*');不会与Autorization头工作。只需启用飞行前请求,使用cors 库:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.options('*', cors())
回答by user1713059
For anyone getting this using ServiceStack backend; add "Authorization" to allowed headers in the Cors plugin:
对于使用 ServiceStack 后端获取此信息的任何人;将“授权”添加到Cors 插件中允许的标题:
Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization"));
Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization"));
回答by Shubham Verma
First you need to installcorsby using below command :
首先,您需要cors使用以下命令进行安装:
npm install cors --save
Now add the following codeto your app starting file like ( app.js or server.js)
现在将以下代码添加到您的应用程序启动文件中,例如 ( app.js or server.js)
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
//enables cors
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
require('./router/index')(app);
回答by user441058
If you don't want to install the cors library and instead want to fix your original code, the other step you are missing is that Access-Control-Allow-Origin:* is wrong. When passing Authentication tokens (e.g. JWT) then you must explicitly state every url that is calling your server. You can't use "*" when doing authentication tokens.
如果您不想安装 cors 库而是想修复您的原始代码,那么您缺少的另一个步骤是 Access-Control-Allow-Origin:* 是错误的。当传递身份验证令牌(例如 JWT)时,您必须明确说明调用您的服务器的每个 url。进行身份验证令牌时不能使用“*”。

