Javascript 拒绝在浏览器中设置不安全的标头“Cookie”错误但请求成功

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28255284/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:29:52  来源:igfitidea点击:

Refused to set unsafe header "Cookie" error in browser yet request is successful

javascriptangularjs

提问by Max Koretskyi

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

我正在使用 Angularjs。当我设置Cookie标题时,xhr.setRequestHeader()我在 Chrome 上收到以下错误:

Refused to set unsafe header "Cookie"

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

但是,Cookie包含在请求中并成功发送到服务器。我似乎已经正确配置了所有内容以允许Cookie服务器和客户端上的标头:

for server I have these:

对于服务器,我有这些:

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

for client I specify these:

对于客户,我指定了这些:

withCredentials

Why is this error?

为什么会出现这个错误?

采纳答案by Seamus

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

您从 Chrome 收到该错误,因为根据XHR 规范,该setRequestHeader方法不应使用禁止的标头名称设置标

Per the specification:

根据规范:

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

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

Instead, for Angular 1.x, set the cookieby using $cookies, and it will be included in subsequent xhrrequests.

相反,角1.x中,设置Cookie使用$cookies,它会被包括在后续xhr请求。

回答by Seamus

This "template" works for me

这个“模板”对我有用



open developer-tools and try run $.ajaxplacing the setRequestHeaderin the beforeSendmethod.开放式开发工具,并尝试运行$.ajax放置setRequestHeaderbeforeSend方法。



<?php
  header('Content-Type: text/html; charset=UTF-8');
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Headers: *');
  header('Access-Control-Expose-Headers: *');
  header('Access-Control-Allow-Credentials: true');
?><!doctype html>
<html lang="en-US">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  </head>
  <body>
    <script defer="defer" src="https://code.jquery.com/jquery-git.js"></script>
  </body>
</html>

taken From Liberated HTML5, and W3C's Cross-Origin Resource Sharing.

取自Liberated HTML5W3C跨域资源共享

回答by lwpro2

if you have the cookies sent over, i think that would be good enough. Having " crossDomain: true, withCredentials: true " solved the issue of "Refused to set unsafe header “Cookie”" i encountered as well. Even though the alert message still there, however, i have the cookie sent over and have correct response back.

如果你把饼干寄过来,我想就足够了。使用“ crossDomain: true, withCredentials: true ”解决了我也遇到的“拒绝设置不安全的标题“Cookie””的问题。然而,即使警报消息仍然存在,我还是将 cookie 发送过来并得到了正确的响应。