Why is the browser not setting cookies after an AJAX request returns?

前端 未结 5 1507
走了就别回头了
走了就别回头了 2020-11-29 00:35

I am making an ajax request using $.ajax. The response has the Set-Cookie header set (I\'ve verified this in the Chrome dev tools). However, the browser does

5条回答
  •  臣服心动
    2020-11-29 01:29

    OK, so I finally figured out the problem. It turns out that setting the Path option is important when sending cookies in an AJAX request. If you set Path=/, e.g.:

    Set-Cookie:SessionId=foo; Path=/; HttpOnly
    

    ...then the browser will set the cookie when you navigate to a different page. Without setting Path, the browser uses the "default" path. Apparently, the default path for a cookie set by an AJAX request is different from the default path used when you navigate to a page directly. I'm using Go/Martini, so on the server-side I do this:

    session.Options(session.Options{HttpOnly: true, Path:"/"})
    

    I'd guess that Python/Ruby/etc. have a similar mechanism for setting Path.

    See also: cookies problem in PHP and AJAX

提交回复
热议问题