- 通过前端proxyTable处理,经试验,添加后,后端可以不用额外处理
proxyTable: {
//可以设置多个,对应到不同的后端服务,通过调用时增加前缀选用不通代理
'/api': {
// 测试环境
target: 'http://127.0.0.1:8080/', // 接口域名,也就是要代理到的后端服务
changeOrigin: true, //是否跨域
pathRewrite: {
'^/api': '' //需要rewrite重写的, 如果前缀是额外增加的,需要重写去掉
}
}
}
- 后端拦截器/过滤器处理(JAVA)
String curOrigin = request.getHeader("Origin");
response.addHeader("Access-Control-Allow-Origin", curOrigin);
response.addHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie, Authorization");
// 跨域会首先发送一次OPTIONS请求,放过
if("OPTIONS".equals(request.getMethod()))
{
return false;
}
3.通过nginx转发
location /api {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' $http_access_control_request_headers;
add_header 'Access-Control-Allow-Methods' *;
proxy_pass http://your ip:8888/api;
}