欢迎来到万象站长学堂!

AJAX相关

当前位置: 主页 > 网络编程 > AJAX相关 > 文章列表

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

时间:2025-10-25 20:11:42|栏目:AJAX相关|点击:18 次

背景

重写一个登录页面,登录接口是跨域接口,重写的页面登录成功后进入页面报错,原因是请求后台接口未携带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相关

下一篇:Ajax实现步骤和原理解析

本文标题:Ajax跨域登录请求未携带cookie错误解决

本文地址:https://zhanzhang.eapis.site/html/2637.html

您可能感兴趣的文章

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:120507403 | 邮箱:120507403@qq.com

Copyright © 2002-2025 万象站长学堂 版权所有沪ICP备2021023961号-8 粤公网安备 13010202004186