django做前后端分离,处理带有cookie的跨域请求

在django前后端分离的项目中,跨域请求是不可避免的,那么怎么去处理这种情况呢,这种情况常见的处理方式就是在settings中用到django-cors-headers,还有在views响应之前将这些处理添加到响应对象中。具体可以参见这篇文章,我觉得还不错:链接

我们项目这里是将这些参数封装好了的,类似在views中的那种方法,只不过放在了装饰器中,具体参数设置:

object["Access-Control-Allow-Origin"] = "*"
object["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS,HEAD"
object["Access-Control-Max-Age"] = "1000"
object["Access-Control-Allow-Credentials"] = "true"
# 关键是头部的信息 要完整 ddd 为自定义 可能有一定关联
object["Access-Control-Allow-Headers"] = "*"

但是最近遇到这个问题是,将Access-Control-Allow-Origin设置为"*"时,前端带着cookie请求时就会报下面的错误:

The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. Origin ‘http://localhost:8080’ is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

因为我们要让前端带cookie请求就要将Access-Control-Allow-Credentials设置为True,而且而且前端在ajax请求中也要将withCredentials设置为true,这样在请求中,若将允许的origin设置为"*"时就会被拒绝,测试时想到的方法是暂时让Access-Control-Allow-Origin设置为前端的ip。

后来查了资料才知道,有cookie了,就是不能设置为 “*”,必须是请求者的ip,这样程序太受限了。

接下来,在对发出的ajax请求的研究中,发现每一个请求中的Origin请求头的值都为"null",于是试着把把后台"Access-Control-Allow-Origin", "*“改成了"Access-Control-Allow-Origin” , “null”,接下来的事情就变得美好了,所有的ajax请求能成功的附带cookie,成功的达到了目的。完美!!!

object["Access-Control-Allow-Origin"] = "null"

猜你喜欢

转载自blog.csdn.net/Panda_813/article/details/82890720
今日推荐