跨域问题原因:
- 浏览器安全问题
- xhr(xmlHttpRequest)才会有跨域问题(其他浏览器请求)
- img ,svg,link,script不存在
- 跨域(协议,域名,端口)
跨域请求的流程
1、当浏览器发现访问的协议,域名,端口不一致,接口会发送请求到后端;
2、如果后端发现跨域的访问,没有做filter或者nginx的代理处理跨域请求,那么浏览器报错;
3、如果后端处理filter,或者ngixn…跨域处理,浏览器不会报错;
解决跨域的方案:
1、前后端做跨域处理;filter,ngixn,Apache
2、前端不发起跨域请求,nginx 作为http服务发送请求;
针对以上跨域问题如何解决
1、客户端修改:移动端开发,可以在chrome不跨域设置,进行联调;
- 找到chorme.exe的文件,右键 dos is here
- chrome —disable-web-security —user-data-dir= 一个文件地址
2、jsonp方案 :只有xhr请求有跨域,使用加载script,通过callback,但是不推荐;
动态创建script,发送请求会携带参数callback
Load成功后再删除script标签
这个参数是前后端约定的,可以修改
Jsonp后端需要把返回值从json转换成执行js
Callback的值作为函数,json作为参数,执行。
Cache是增加请求的参数,时间戳等等
发送类型是script不是xhr
缺点
后端需要改动
不是xhr的类型
不支持其他请求类型,只有get
3、修改被调用方【支持跨域】、修改调用方【隐藏跨域】
clinet -> apach/nginx -> tomact
client:客户端
apach/nginx:http服务器
tomact:应用服务器
静态请求流程(js,css,img):
动态请求流程
client -> http服务器 -> 应用服务器;
应用服务器 -> http服务器 -> client;
http服务器作用:
处理静态请求,负载均衡;
常见跨域问题
1、跨域携带cookie
是否携带cookie:withCredential === true;以及
access control from origin 不能为*;
参考文献:https://blog.csdn.net/menghuanzhiming/article/details/102736312
request会携带请求头origin;
后段判断如果是跨域,设置origin,获取request的origin属性,设置origin
2、跨域携带自定义header
access control allow headers
解决方案
1、被调用实现方案 应用服务器@filter ;
被调用方设置响应头,允许跨域(cros跨域资源共享),携带cookie…
2、被调用实现方案:nginx实现后端的filter
真实服务器地址:localhost:8080/test/xxx.json;
ihost绑定:127.0.0.1 b.com
nginx:
server{
listen 80;
server_name b.com
location /{
proxy_pass http://localhost:8080/
}
}
访问 b.com/test/xxx.json;
接口被转发到http://localhost:8080/test/xxx.json; 成功
删除后端localhost:8080的filter;配置nginx;
server{
listen 80;
server_name b.com
location /{
proxy_pass http://localhost:8080/
固定
add_header Access-Control-Allow-Methods *;
add_header Access-Control-Max-Age 3600;
add_header Acess- Control-Allow-Credential true;
动态
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Headers $http_accss_control_Request-Headers
预检命令在nginx返回;
if ($request_method = OPTIONS){
return 200
}
}
}
// frontend 启动服务 localhost:8081;调用ajax
$.ajax({url:’http://b.com/get1'}).then()
发送的接口缺少cookie现象,也是跨域的提示现象;
在b.com 添加cookie;不是在前端服务localhost:8081;
发送的cookie是被调用方的cookie
client -> http -> server
请求发送到http地址 http 必须有cookie,代理转发server
http,nginx设置filter请求头
3、被调用实现方案 apache
配置虚拟主机
httpd.conf 开启虚拟配置httpd-vhosts.conf
4、被调用实现方案 spring
增加注视 @crossOrigin
6、调用方跨域 隐藏跨域 反向代理;
访问同一个域名的,两个不同url,最后访问两个不同的服务器;
请求地址是相对地址,相同域名下的后段去访问;
实践:
hots:
127.0.0.1 b.com a.com 新增a.com调用方的虚拟主机
nginx:
所有请求转发到8081端口;
调用的服务器地址代理为ajaxserver
server{
listen 80;
server_name a.com
location /{
proxy_pass http://localhost:8081/
}
location /ajaxserver{
proxy_pass http://localhost:8080/test/
}
}
//frontend 域名 a.com;
$.ajax({url:’/ajaxserver/get1’}).then()
浏览器访问相对地址就不会跨域;
参考文献:https://segmentfault.com/a/1190000011145364
浏览器的访问伴随的问题
同源策略
含义:同协议,同域名,同端口简称同源
表现:
- 访问数据资源,cookie,localStorage,session,indexDB…
- 访问网络资源,xhr跨站点访问
- 操作DOM
1、XSS攻击
原理:
html是超文本标记语言,浏览器会识别特殊字符<,&… 当作标签或者js解析,所以当数据被恶意注入