AJAX相关

关注公众号 jb51net

关闭
首页 > 网络编程 > AJAX相关 > Ajax请求未携带cookie

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

作者:DQuery

这篇文章主要为大家介绍了Ajax跨域登录请求未携带cookie错误解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

背景

重写一个登录页面,登录接口是跨域接口,重写的页面登录成功后进入页面报错,原因是请求后台接口未携带cookie,但是通过老页面进行登录,进入页面后cookie可以正常携带,使用工具对比新老页面登录请求,request和response都是一样。

解决

排除过以下可能性

对比过两边的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。

参考文档

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

您可能感兴趣的文章:
阅读全文