CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权 [英] CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
问题描述
我正在尝试将请求从一个本地主机端口发送到另一个.我在前端使用 angularjs,后端使用节点.
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.
因为是 CORS 请求,所以在 node.js 中,我使用
Since it is CORS request, In node.js, i am using
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');
在 angular.js 服务文件中,我正在使用
and in the angular.js service file, I am using
return {
getValues: $resource(endpoint + '/admin/getvalues', null, {
'get': {
method: 'GET',
headers:{'Authorization':'Bearer'+' '+ $localStorage.token}
}
}),
}
我收到以下错误
预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权.
请帮忙!
推荐答案
您还必须在允许的标题中添加选项.浏览器在发送原始请求之前发送预检请求.见下文
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');
来自https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
在 CORS 中,发送带有 OPTIONS 方法的预检请求,以便服务器可以响应是否可以使用这些参数发送请求.Access-Control-Request-Method
标头作为预检请求的一部分通知服务器,当实际请求发送时,它将使用 POST 请求方法发送.Access-Control-Request-Headers
标头通知服务器,当实际请求被发送时,它将与 X-PINGOTHER
和 Content-Type 一起发送
自定义标题.在这些情况下,服务器现在有机会确定它是否希望接受请求.
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-Method
header 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-Headers
header notifies the server that when the actual request is sent, it will be sent with aX-PINGOTHER
andContent-Type
custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.
已编辑
您可以通过使用 npmjs.com/package/cors npm 包来避免这种手动配置.我有也用过这个方法,简单明了.
You can avoid this manual configuration by using npmjs.com/package/cors npm package.I have used this method also, it is clear and easy.
这篇关于CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!