vue 前端 springboot 后端分离跨域求解
跨域的原理是浏览器为了安全而阻止。如果浏览器发现服务器 header 告诉它允许就可以。高德的 api 跨域就是这个原理。
有图有真相,你试试: https://shoujihao.zhishifufei.cn/
以上为本人解决方式,仅供参考
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping(“/**”)
.allowedOrigins(“*”)
.allowCredentials(true)
.allowedMethods(“GET”, “POST”, “PUT”, “DELETE”, “OPTIONS”)
.allowedHeaders(“*”);
}
“`
server {
listen 85;
location / {
root /usr/local/app/hr/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8091/sxwendu;
}
}
还有一种方法是前端代码 build 到后端的目录里,用 SpringBoot 作为静态文件服务器。
然后在重写的 configure 方法中, 添加
“`
// 禁用 CSRF
http.csrf().disable();
// 禁用表单登录
http.formLogin().disable();
// 防止 iframe 造成跨域
http.headers().frameOptions().disable();
// 开启跨域
http.cors();
“`
在实现 AuthenticationFailureHandler 接口的 handler 中添加
“`
// 跨域 options 请求直接返回
if (Objects.equals(request.getMethod(), HttpMethod.OPTIONS.toString())) {
return;
}
“`
private CorsConfiguration build() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedOrigin(“*”);
configuration.addAllowedHeader(“*”);
configuration.addAllowedMethod(“*”);
configuration.addExposedHeader(“content-disposition”);
configuration.setMaxAge(3600L);
return configuration;
}
如果不携带 cookies 跨域,axiosCredentials 设置为 false 就行了。
一般都是塞到后端程序的项目里面,如果要分开的话一般都是 Nginx 代理。
跨域是浏览器的安全策略。postman 不存在这个策略。