跨域报错:Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
1、为什么会出现跨域
出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)
2、什么是跨域
当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域
当前页面url | 被请求页面url | 是否跨域 | 原因 |
---|---|---|---|
http://www.baidu.com/ | http://www.baidu.com/index.html | 否 | 同源(协议、域名、端口号相同) |
http://www.baidu.com/ | https://www.baidu.com/index.html | 跨域 | 协议不同(http/https) |
http://www.baidu.com/ | http://www.google.com/ | 跨域 | 主域名不同(google/baidu) |
http://www.baidu.com/ | http://blog.baidu.com/ | 跨域 | 子域名不同(www/blog) |
http://www.baidu.com:8080/ | http://www.baidu.com:8888/ | 跨域 | 端口号不同(8080/8888) |
3、跨域请求解决办法(Django)
3-1、安装第三方扩展:
pip install django-cors-headers
3-2、添加应用:
INSTALLED_APPS = (
...
'corsheaders',
...
)
3-3、第三步,添加中间件,注意放在第一条,第一时间进行处理:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
3-4、配置访问规则或白名单:
允许所有域名跨域(优先选择)
CORS_ORIGIN_ALLOW_ALL = True
配置白名单
CORS_ORIGIN_WHITELIST = (
'*'
# '127.0.0.1:8000',
# 'localhost:8000',
# '127.0.0.1:8080',
# 'localhost:8080',
# 'ads-cms-api.aataotao.com:8000' #
# 'taoduoduo-test.oss-cn-shenzhen.aliyuncs.com:80', # 线上
# '10.0.2.187:8080' # 本地
)
3-5、允许携带Cookie:
CORS_ALLOW_CREDENTIALS = True
注意:
如果使用了Nginx:则配置如下规则:
sudo vim /usr/local/nginx/conf/nginx.conf
location / {
proxy_pass 127.0.0.1:8000/;
}