关于ajax:一次Ajax请求未携带cookie问题排查

7次阅读

共计 1579 个字符,预计需要花费 4 分钟才能阅读完成。

背景

重写一个登录页面,登录接口是跨域接口,重写的页面登录胜利后进入页面报错,起因是申请后盾接口未携带 cookie,然而通过老页面进行登录,进入页面后 cookie 能够失常携带,应用工具比照新老页面登录申请,request 和 response 都是一样。

解决

排除过以下可能性

  • 在代码中进行 cookie 删除
  • 两个申请头不一样导致后果不一样
  • 零碎工夫设置谬误,导致 cookie 过期

比照过两边的 ajax 申请代码,的确都是一样,甚至通过工具一一字节进行比照也是一样,最初发现在老页面一个暗藏的角落有一行这个代码

$.ajaxSetup({
    dataType: "json",
    async: true,
    xhrFields: {withCredentials: true},
});

在新页面加上后问题解决。其中外围的就是 withCredentials: true 这个配置,通过查问官网文档,理解到如果跨域申请须要带上 cookie 必须设置改参数,官网上是这么形容的

The XMLHttpRequest.withCredentials property is a boolean value that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-origin requests.

In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is false. XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.

这里简略翻译下

XMLHttpRequest.withCredentials 是一个 boolean 类型的属性,用于跨域申请时进行认证,比方 cookie,认证头(authorization headers)或者 TLS 客户端证书。当申请是同域时该属性生效。

另外,这个参数也示意是否能够疏忽响应 cookie,默认是 false(也就是疏忽 cookie),如果没有设置为 true,XMLHttpRequest 进行的跨域申请响应的 cookie 无奈设置到该域下,设置 withCredentials=true 后,同域 cookie 策略依然实用于第三方 cookie,也就是无奈通过 document.cookie 获取响应的 cookie。

参考文档

  • https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
  • https://code.yidas.com/javascriptjquery-ajax-cross-domain-request-with-credentials/
  • https://api.jquery.com/jquery.ajax/
正文完
 0