错误信息:
Access to XMLHttpRequest at '服务器地址' from origin 'http://127.0.0.1:8080' 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.
原因
这是由于ajax跨域访问引起的。所谓跨域就是,在www.aaa.com域下,访问www.bbb.com域下的资源;出于安全的考虑浏览器允许跨域写,而不允许跨域读,写就是上行(发送请求send reques),读就是下行(接受响应receive response)。
解决方法
1. 临时解决方法: 给chrome浏览器添加参数
windows下打开cmd命令进入chrome浏览器目录,执行以下命令
chrome.exe --disable-web-security --user-agent="Android" --user-data-dir="C:/temp-chrome-eng
2.永久解决方法:安装django-cors-headers
pip install django-cors-headers
在settings.py中增加:
INSTALLED_APPS = (
...
'corsheaders',
...
)
...
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware' ,
'django.middleware.common.CommonMiddleware' ,
...
]
CORS_ORIGIN_ALLOW_ALL = True