Refusing to set unsafe cookie header error in browser, but request successful

I am using Angularjs. When I set the Cookie header with xhr.setRequestHeader() , I get the following error in Chrome:

 Refused to set unsafe header "Cookie" 

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

for the server I have:

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

for the client I indicate:

 withCredentials 

Why is this a mistake?

+6
source share
3 answers

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

In the specification:

This is prohibited, so the user agent remains fully above them.

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

+2
source

This "pattern" works for me

<h / "> open the developer tools and try running $.ajax by putting 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 Exempted HTML5 and W3C Cross-Sourcing .

+1
source

If you have uploaded files, I think it will be good enough. Having "crossDomain: true, withCredentials: true" solved the problem "Refused to set the unsafe header" Cookie "" I also encountered. Despite the fact that there is still a warning message, I sent a cookie and returned the correct answer.

0
source

Source: https://habr.com/ru/post/981816/


All Articles