一、错误提示
No 'Access-Control-Allow-Origin' header is present on the requested resource.
什么是CORS
上面的问题就是由CORS
引起的,什么是CORS?
CORS(跨域资源共享,Cross-Origin Resource Sharing)是一种跨域访问的机制,可以让Ajax实现跨域访问。
其实,在服务器的response header中,加入 " Access-Control-Allow-Origin: *" 即可支持CORS
二、跨域方案
1、使用JSONP
使用Ajax获取json数据时,存在跨域的限制。
不过,在Web页面上调用js的script脚本文件时却不受跨域的影响,JSONP就是利用这个来实现跨域的传输。
因此,我们需要将Ajax调用中的dataType从JSON改为JSONP(相应的API也需要支持JSONP)格式。
JSONP只能用于GET请求。
2、直接修改Django中的views.py文件
修改views.py中对应API的实现函数,允许其他域通过Ajax请求数据: {{< highlight python >}} 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 {{< /highlight >}}
3、安装django-cors-headers
来自GitHub的库,django-cors-headers
用于处理跨源资源共享(CORS)所需的服务器头的Django应用程序
使用之前要注意一下使用范围: * 支持Python 3.5-3.7 * Django 1.11-2.2支持
安装django-cors-headers:
pip install django-cors-headers
必要的添加,在setting.py
文件中
INSTALLED_APPS = (
...
'corsheaders',
...
)
...
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
分享一下个人的其他配置(如果有安全性考虑请不要照抄,尤其是第一行....),具体请看GitHub官方配置页
# 跨域设置
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = []
CORS_ALLOW_METHODS = [
' DELETE ',
' GET ',
' OPTIONS ',
' PATCH ',
' POST ',
' PUT ',
]
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
CORS_ALLOW_CREDENTIALS = True
X_FRAME_OPTIONS = 'ALLOWALL'
SECURE_HSTS_SECONDS = 3600