Ajax跨域登录请求未携带cookie错误解决

2024-03-01 0 198
目录
  • 背景
  • 解决
    • 新页面加上后问题解决

背景

重写一个登录页面,登录接口是跨域接口,重写的页面登录成功后进入页面报错,原因是请求后台接口未携带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/
  • https://www.jb51.net/article/225438.htm

以上就是Ajax跨域登录问题请求未携带cookie错误解决的详细内容,更多关于Ajax请求未携带cookie的资料请关注悠久资源网其它相关文章!

您可能感兴趣的文章:

  • ajax请求前端跨域问题原因及解决方案
  • Ajax跨域请求COOKIE无法带上的完美解决办法
  • Ajax跨域访问Cookie丢失问题的解决方法
  • 解决ajax跨域请求数据cookie丢失问题
  • JS获取dom 对象 ajax操作 读写cookie函数

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 AJAX相关 Ajax跨域登录请求未携带cookie错误解决 https://www.u-9.cn/biancheng/ajax/180991.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务