背景
重写一个登录页面,登录接口是跨域接口,重写的页面登录胜利后进入页面报错,起因是申请后盾接口未携带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/