1.跨域条件
由于浏览器的同源策略,用来限制从一个源加载的文档或脚本与来自另一个源的资源进行交互。同源要同时满足以下3个条件:
协议相同
端口相同
主机相同
2.常见跨域情况
网络协议不同,如http协议访问https协议 ;
端口不同 ;
域名或子域名不同,如www.baidu.com访问www.qq.com,tieba.baidu.com访问 pan.baidu.com;
3.如何解决
在nginx.conf的server节点上添加相应的跨域配置即可,如下所示:
user root;
events {
worker_connections 1024;
}
http {
charset utf-8;
server {
listen 80;
server_name 127.0.0.1;
#允许跨域请求的域,* 代表所有
add_header 'Access-Control-Allow-Origin' *;
#允许带上cookie请求
add_header 'Access-Control-Allow-Credentials' 'true';
#允许请求的方法,GET/POST/PUT/DELETE
add_header 'Access-Control-Allow-Methods' *;
#允许请求的header
add_header 'Access-Control-Allow-Headers' *;
location /index.html {
alias /opt/nginx/html/index.html;
}
}
server {
listen 81;
server_name 127.0.0.1;
#允许跨域请求的域,* 代表所有
add_header 'Access-Control-Allow-Origin' *;
#允许带上cookie请求
add_header 'Access-Control-Allow-Credentials' 'true';
#允许请求的方法,GET/POST/PUT/DELETE
add_header 'Access-Control-Allow-Methods' *;
#允许请求的header
add_header 'Access-Control-Allow-Headers' *;
location /index.html {
alias /opt/nginx/html/index.html;
}
}
}