1. 跨域
1.1 基本概念
详细可查看MDN的 浏览器的同源策略
1.2 example
下表给出了与 URL store.company.com/dir/page.ht… 的源进行对比的示例:
URL | 结果 | 原因 |
---|---|---|
store.company.com/dir2/other.… | 同源 | 只有路径不同 |
store.company.com/dir/inner/a… | 同源 | 只有路径不同 |
store.company.com/secure.html | 失败 | 协议不同 |
store.company.com:81/dir/etc.htm… | 失败 | 端口不同 ( http:// 默认端口是80) |
news.company.com/dir/other.h… | 失败 | 主机不同 |
2.代理
2.1正向代理
2.2反向代理
代理客户端的请求,并按照一定的规则,把请求分发给其它服务器
3.nginx
3.1 基本概念
- Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。占有内存少,并发能力强。
3.2 example
页面:example.com
接口:api.example.com
在页面上请求接口不做任何配置的话,浏览器会提示跨域,因为违反了浏览器的同源策略。
3.3 通过反向代理来解决跨域
可以通过路径来区分:
example.com # 请求页面
example.com/api/ # 请求接口
# config
server {
listen 80;
server_name example.com;
location / {
root /;
index index.html index.htm;
}
location /api/ {
proxy_pass http://api.example.com/api;
}
}
复制代码
把请求 example.com/api/ 代理到 api.example.com
这样资源就算在同一域名下,不存在夸域的问题了。
3.4 通过配置header来解决跨域
- 主要是设置Access-Control-Allow-等相关属性,来让浏览器知道,网站允许哪些域名、哪种请求方式的请求。
- 浏览器遇到跨域请求是会先发送OPTIONS请求预检
- 这种设置header的方式,请求然会是跨域,但是因为服务端的允许,所以跨域请求是通畅的。
在api.example.com在的服务器做配置,允许来自example.com网站的跨域请求资源
server {
listen 80;
server_name api.example.com;
add_header 'Access-Control-Allow-Origin' ‘http://example.com’; # 允许的origin, 可以为*,带cookie的请求不支持*
add_header 'Access-Control-Allow-Credentials' 'true'; # 为 true 可带上 cookie
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # 允许请求方法
add_header 'Access-Control-Allow-Headers' '*'; # 可以具体设置
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
# OPTIONS 请求的有效期,在有效期内不用发出另一条预检请求
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
location / {
root /;
index index.html index.htm;
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END