CORS错误:请求标头字段预检响应中的Access-Control-Allow-Headers不允许授权 [英] CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
问题描述
我正在尝试将请求从一个localhost端口发送到另一个端口。我在前端使用 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 请求,所以在节点中.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. The Access-Control-Request-Headers
header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER
and Content-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 package。我也使用过这种方法,很简单明了。
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屋!