且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

拒绝设置不安全的头部“Cookie"浏览器出错但请求成功

更新时间:2022-10-19 15:06:16

您从 Chrome 中收到该错误,因为根据 XHR 规范setRequestHeader 方法不应设置带有 禁止的标题名称.

根据规范:

这些是被禁止的,因此用户代理仍然可以完全控制它们.

相反,对于 Angular 1.x,设置 cookie 使用$cookies,它会包含在后续的 xhr 请求中.

I'm using Angularjs. When I set Cookie header with xhr.setRequestHeader() I get the following error on Chrome:

Refused to set unsafe header "Cookie"

However, the Cookie is included into the request and successfully sent to server. I seem to have configured everything correctly to allow Cookie header on server and client:

for server I have these:

Header add Access-Control-Allow-Credentials "true"

for client I specify these:

withCredentials

Why is this error?

You get that error from Chrome because, per the XHR specification, the setRequestHeader method should not set headers with a forbidden header name.

Per the specification:

These are forbidden so the user agent remains in full control over them.

Instead, for Angular 1.x, set the cookie by using $cookies, and it will be included in subsequent xhr requests.