Setting a cookie on a subdomain from an ajax request

后端 未结 1 910
感情败类
感情败类 2020-12-13 05:57

I have a webapp on www.example.com and an API on api.example.com.

The webapp makes ajax calls to the API.

Somewhere I need to put a cookie on api.example.com

相关标签:
1条回答
  • 2020-12-13 06:16

    Set the allow Credentials header on api

    Access-Control-Allow-Credentials: true
    

    Use withCredentials for the request

    $.ajax({
        url: a_cross_domain_url,
        xhrFields: { 
            withCredentials: true 
        }
    });
    

    Otherwise the XMLHttpRequest will not send the cookies, regardless of the Access-Control-Allow-Credentials header.

    Remove the wildcard on Access-Control-Allow-Origin

    Access-Control-Allow-Origin: http://www.example.com
    

    The wildcard * will not work. The browser will discard the response if withCredentials was set.

    References:

    http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/

    https://developer.mozilla.org/en-US/docs/HTTP_access_control

    http://arunranga.com/examples/access-control/credentialedRequest.html

    http://api.jquery.com/jQuery.ajax/

    0 讨论(0)
提交回复
热议问题