Max Koretskyi
Max Koretskyi

Reputation: 105537

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

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?

Upvotes: 17

Views: 58750

Answers (3)

Seamus
Seamus

Reputation: 4829

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.

Upvotes: 14

Jackie
Jackie

Reputation: 25989

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.

Upvotes: 0

user257319
user257319

Reputation:

This "template" works for me


open developer-tools and try run $.ajax placing the setRequestHeader in the beforeSend method.


<?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.

Upvotes: 0

Related Questions