背景
重写一个登录页面,登录接口是跨域接口,重写的页面登录成功后进入页面报错,原因是请求后台接口未携带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://api.jquery.com/jquery.ajax/
以上就是ajax跨域登录问题请求未携带cookie错误解决的详细内容,更多关于ajax请求未携带cookie的资料请关注代码网其它相关文章!
发表评论