失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 请求跨域设置同时允许cookie跨域(携带cookie)

请求跨域设置同时允许cookie跨域(携带cookie)

时间:2022-11-01 10:45:44

相关推荐

请求跨域设置同时允许cookie跨域(携带cookie)

最近做一个前后端分离的项目,后台.Net 进行开发,使用session来进行身份验证。发现调用接口的时候总是显示未登录,经过检查发现每次请求过去的sessionid是不一样的,导致服务器找不到之前登陆时候的session从而获取不到数据。

查了下资料了解到浏览器不允许cookie跨域传递,导致登陆请求写入cookie的sessionid 在下一个请求发起的时候并不能带出来发送给服务器,从而导致每次的session都是不同的session导致后台的身份验证没有作用。

解决过程: 查阅资料发现同时设置 允许跨域Access-Control-Allow-Origin:"*" 允许cookie跨域"Access-Control-Allow-Credentials", "true" 前端设置 withCredentials: true 前端代码

let options = new RequestOptions({ headers: new Headers({ 'Content-Type': 'application/json' }),withCredentials: true });复制代码

设置完成之后发现依然报错查阅发现 Access-Control-Allow-Origin:"" 和 Access-Control-Allow-Credentials", "true" 同时设置的时候Access-Control-Allow-Origin不能设置为"",只能设置为具体的域名,所以后面这样设置

System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + "://" + System.Web.HttpContext.Current.Request.UrlReferrer.Authority);复制代码

一个取巧的方式去获取域名设置。 再次测试发现依然报错 查看报错信息 XMLHttpRequest cannot load http://localhost:28694/WeChatApp/GetAppSession?encryptparam=hxTdRDipfsBUemx…jiQmA7TiulXaXjZSCdl5X2L5bGlBxFQPUelfcBPLzVr7ZWV5CtA%3D%3D&headver=1.71.1.1. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is 'true, true'. It must be 'true' to allow credentials. Origin 'http://localhost:8081' is therefore not allowed access. vendor.d892748….bundle.js:197 ERROR e {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: t…} 中出现了'true,true'再加上之前 [图片上传失败...(image-8f7981-1511316910517)] 推测这里设置的 "Access-Control-Allow-Credentials", "true"被重复设置了应该是哪里已经设置过了,故而注释掉 最后C#代码

System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + "://" + System.Web.HttpContext.Current.Request.UrlReferrer.Authority);// System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");复制代码

测试通过解决

如果觉得《请求跨域设置同时允许cookie跨域(携带cookie)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。