Arm144
Arm144

Reputation: 773

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"

Upvotes: 16

Views: 58270

Answers (2)

Mukendi Emmanuel
Mukendi Emmanuel

Reputation: 198

When you request server side and you need to set cookie.

            var setCookie = xhr.getResponseHeader('set-cookie');

if the server your requested is on http this error will apear. on Chrom maybe others too. so you juste to request an https server. next when u found an unsafe error on navigator remind that is according to http. replace it by https

Upvotes: 0

Quentin
Quentin

Reputation: 944116

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.

Upvotes: 23

Related Questions