1、以前用的土办法:配置个head头,就可以了。
response = JsonResponse({"msg":"ok","status":1})
response['Access-Control-Allow-Origin'] = '*'
return response
2、然后用扩展的办法,不用每次返回时候都写这句话。
(1)安装django-cors-headers,详情请看官方文档
pip install django-cors-headers
(2)配置settings.py文件,在INSTALLED_APPS里添加“corsheaders”
INSTALLED_APPS = [
...
'corsheaders',
...
]
(3)在MIDDLEWARE_CLASSES添加 ‘corsheaders.middleware.CorsMiddleware’, ‘django.middleware.common.CommonMiddleware’
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
(4)在setting.py底部添加
#跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ()
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
OK,结束!