Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookie in header javascript error "Refused to set unsafe header "Cookie""

I have check all the post about setting the cookie via Header, and I always see that the people recommend put this:

withCredentials: true

I'm trying to do it and got the same error.

 $scope.myAppsLoginResponse = JSON.stringify(response.data, null, 3);
        var dataC = JSON.parse($scope.myAppsLoginResponse);
        $cookies.cookie = 'Somethin here as cookie';

        var userId = dataC.user_id;
        var thePath = '/thePath';
        var theURL = 'https://theUrl';

        var cookieRes = $cookies.cookie;
        document.cookieMyApp = cookieRes;

        var headers2 = {};
            headers2 ['Accept-Language'] = 'es-ES';
            headers2 ['Cookie'] = document.cookieMyApp;
            headers2 ['Authorization'] = 'Basic Z2743ASasdh23Q=';

        var param = {}
            param ['userId'] = userId;

        var req2 = {
            method: 'GET',
            url: theURL + thePath ,
            headers: headers2,
            params: param,
            xhrFields: {
                withCredentials: true
             }
        }

Response:

Refused to set unsafe header "Cookie"

like image 547
Arm144 Avatar asked Dec 30 '25 11:12

Arm144


1 Answers

JavaScript cannot set cookie headers explicitly.

You can use document.cookie to set a cookie for the current origin.

You can use withCredentials: true so that previously set cookies will be sent with a cross-origin Ajax request.

There is no way to change the cookies for a different origin from the current origin although you could set location.href to cause the browser to navigate to a URL on the other origin that will send a set-cookie header and redirect back to your page.


Since you are making a same origin request all you need to do is set document.cookie before you make the request.

like image 141
Quentin Avatar answered Jan 02 '26 04:01

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!