python django在处理跨域请求的时候,提示
Access to XMLHttpRequest at 'http://10.237.221.64:8000/api/projects/all_projects' from origin 'http://localhost:8001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
翻译过来就是: 前端在通过http://localhost:8001访问接口的时候,被CORS策略阻止
网上的解决办法都试了之后,还是不行,最后经检查,是因为django升级了版本,setting的设置有一些变化,采用如下解决办法之后,可以成功
1. 安装django-cors-headers
pip3 install django-cors-headers
2. 配置settings.py文件
INSTALLED_APPS = [
'corsheaders',
]
# 跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
]
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
'Access-Control-Allow-Origin',
)
然后启动python3 manage.py runserver 0.0.0.0:8000 ,前端重新请求,问题解决!