同源策略
浏览器的同源策略:是一种约定,是浏览器最核心也是最基本的安全功能,如果浏览器少了同源策略,则浏览器的正常功能可能都会受到影响。
同源: 协议、域名(IP)、端口相同即为同源
- 跨域
有两台服务器分别为A,B,如果从服务器A的页面发送异步请求到服务器B获取数据,如果服务器A和服务器B不满足同源策略,则就会出现跨域问题。
- 案例
```css
协议不同,跨域
http://192.168.200.131/user/1 https://192.168.200.131/user/1
ip不同,跨域
http://192.168.200.131/user/1 http://192.168.200.132/user/1
端口不同,跨域
http://192.168.200.131/user/1 http://192.168.200.131:8080/user/1
域名不同,跨域
http://www.nginx.com/user/1 http://www.nginx.org/user/1
默认端口为80 同源
http://www.nginx.org:80/user/1 http://www.nginx.org/user/1
<a name="fpIJ4"></a>
# 跨域案例
1. 在nginx安装目录下的html目录建立一个corss.html文件,文件内容如下,该页面的作用就通过按钮访问不同端口的服务。
```html
<html>
<head>
<meta charset="utf-8">
<title>跨域问题演示</title>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
<script>
$(function(){
$("#btn").click(function(){
$.get('http://172.41.100.15:8076/data',function(data){
alert(JSON.stringify(data));
});
});
});
</script>
</head>
<body>
<input type="button" value="获取数据" id="btn"/>
</body>
</html>
配置nginx服务
server{
listen 8076;
server_name localhost;
location /data{
default_type application/json;
return 200 '{"id":1,"name":"TOM","age":18}';
}
}
server{
listen 80;
server_name localhost;
location /{
root html;
index corss.html;
}
}
访问
http://172.41.100.15/
跨域解决
解决跨域问题,需要添加两个头信息,一个是Access-Control-Allow-Origin
,Access-Control-Allow-Methods
Access-Control-Allow-Origin: 直译过来是允许跨域访问的源地址信息,可以配置多个(多个用逗号分隔),也可以使用*
代表所有源
Access-Control-Allow-Methods:直译过来是允许跨域访问的请求方式,值可以为 GET POST PUT DELETE…,可以全部设置,也可以根据需要设置,多个用逗号分隔,
- 配置案例
server{
listen 8076;
server_name localhost;
location /data{
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods *;
default_type application/json;
return 200 '{"id":1,"name":"TOM","age":18}';
}
}
server{
listen 80;
server_name localhost;
location / {
root html;
index corss.html;
}
}