Prevent Cookies From Being Sent on AJAX Request

前端 未结 5 1156
庸人自扰
庸人自扰 2021-02-05 00:58

I have a web service that I invoke from script but that does not need any information stored in cookies. Anytime I make a request to the service, the cookie is sent along with i

相关标签:
5条回答
  • 2021-02-05 01:10

    The withCredentials flag is needed to actually send cookies with cross-origin ajax calls.

    See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

    Setting it to false will prevent cookies from being sent.

    With same-origin requests you will need to follow the other answers mentioned here.

    0 讨论(0)
  • 2021-02-05 01:22

    No, the cookie will always be sent.

    You could how your cookies are sent to the browser, and use the http flag on them, which means they won't be sent via javascript.

    Or (which lots of sites use), create a new subdomain which you never sent any cookies on.

    0 讨论(0)
  • 2021-02-05 01:25

    You are correct in saying that browsers send matching (path + domain + session) cookies along with the HTTP request. This is critical for the cookie mechanism to work.

    Couldn't you simply, not read the cookies?

    Additionally, when the cookie is originally set, you can set what directory (and its subdirectories) can access the cookie.

    For example, if you set a cookie to be read in /foo/bar/ only, a file located in /whatever/ajaxHandler.php cannot see those those cookies.

    Check this out: http://us.php.net/setcookie

    While I'm not sure if you're using PHP, it could be a good starting point for you.

    0 讨论(0)
  • 2021-02-05 01:29

    Another approach would be prior to doing $.ajax:
    1. get the cookies from the browser for your domain with javascript (save them in a global variable)
    2. delete the cookies for your domain with javascript from the browser
    3. do the $.ajax call
    4. place the cookies (from the global variable) back in the browser.

    If you don't need the cookies from your domain at all just delete them (so skip 1. and 4.).

    0 讨论(0)
  • 2021-02-05 01:31

    Send AJAX requests to cookie-less subdomain on your server. So you app is www.mydomain.com and ajax requests are served from api.mydomain.com which you never set a cookie on. Also a great idea to do this with static files like images etc...

    see the "Use Cookie-free Domains for Components" section of http://developer.yahoo.com/performance/rules.html

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