1.使用JSONP
使用Ajax获取json数据时,存在跨域的限制。不过,在Web页面上调用js的script脚本文件时却不受跨域的影响,JSONP就是利用这个来实现跨域的传输。因此,我们需要将Ajax调用中的dataType从JSON改为JSONP(相应的API也需要支持JSONP)格式。
JSONP只能用于GET请求。
2.直接修改Django中的views.py文件
修改views.py中对应API的实现函数,允许其他域通过Ajax请求数据:
-
def myview(_request):
-
response = HttpResponse(json.dumps({"key": "value", "key2": "value"}))
-
response["Access-Control-Allow-Origin"] = "*"
-
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
-
response["Access-Control-Max-Age"] = "1000"
-
response["Access-Control-Allow-Headers"] = "*"
-
return response
3.安装django-cors-headers
这里还有一各发现!在Django中,有人开发了CORS-header的middleware,只在settings.py中做一些简单的配置即可,见:https://github.com/ottoyiu/django-cors-headers/现在用起来服务器端完全开放,开启CORS,没有跨域烦恼,真爽!~
安装django-cors-headers:
pip install django-cors-headers
在settings.py中增加:
-
INSTALLED_APPS = (
-
...
-
'corsheaders',
-
...
-
)
-
...
-
MIDDLEWARE_CLASSES = (
-
...
-
'corsheaders.middleware.CorsMiddleware',
-
'django.middleware.common.CommonMiddleware',
-
...
-
)
可以配置允许跨域访问的白名单或者直接设置为允许所有的跨域访问,具体的配置可以看看他们的github页说明 --------------------- 本文来自 开开136 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/kaikai136412162/article/details/79657744?utm_source=copy