django3.0解決CORS跨域問題
阿新 • • 發佈:2020-12-24
技術標籤:django
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",
]