CORS跨域问题:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/v1/login/' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
1.安装
pip install django-cors-headers
2.添加应用
INSTALLED_APPS = (
...
'corsheaders',
...
)
3.设置中间件
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
4.设置CORS跨域白名单配置
# 放行全部
CORS_ORIGIN_ALLOW_ALL = True
# 允许携带cookie
CORS_ALLOW_CREDENTIALS = True
# 指定域名端口放行(推荐)
CORS_ORIGIN_WHITELIST = (
'http://127.0.0.1:8080',
'http://localhost:9528',
)
# 指定请求方式
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
# 指定请求类型
CORS_ALLOW_HEADERS = [
'*',
'dnt',
'source',
'origin',
'Pragma',
'accept',
'user-agent',
'x-csrftoken',
'X_FILENAME',
'content-type',
'authorization',
'authentication',
'XMLHttpRequest',
'accept-encoding',
"x-requested-with",
]