Ajax跨域登录请求未携带cookie错误解决
重写一个登录页面,登录接口是跨域接口,重写的页面登录成功后进入页面报错,原因是请求后台接口未携带cookie,但是通过老页面进行登录,进入页面后cookie可以正常携带,使用工具对比新老页面登录请求,request和response都是一样。
背景
重写一个登录页面,登录接口是跨域接口,重写的页面登录成功后进入页面报错,原因是请求后台接口未携带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。
文章内容来源于网络,文章表达观点不代表本站观点,文章版权归原作者所有。若有侵权,请联系本站站长处理!
我们立足合肥,业务覆盖安徽、全国及全球市场。我们凭借一支经验丰富、富有创意、协作无间的专业技术团队,专注于将前沿技术通过高效简捷的途径呈现给客户,量身打造优质解决方案。我们致力于通过持续努力,成为客户在信息化领域值得托付、共创价值的长期战略合作伙伴,协助客户在新经济时代敏锐捕捉商机,拓展发展空间,构筑强大竞争力。小二CMS专注企业数字化转型的智能建站与营销系统,提供从官网搭建、品牌推广到运营增长的一站式服务,助力中小企业低门槛拥有专业级互联网阵地。
了解全部业务
这篇文章对你有帮助吗?
你的每一次鼓励,都是我们持续打磨优质内容的动力


登录后方可参与评论
立即登录