本文已参与「新人创作礼」活动,一起开启掘金创作之路。 在前后端分离的项目中,前端后端单独开发,虽然效率上变快了,但是遇到最大的坑就是跨域问题。 因为.net项目或者老的java项目,采用的还是前后端不分离的方式,java后端写完前端写后端,都在一个作用域下面,其实没用什么问题。jsp页面其实相当于一个servlet后端代码。只需要把前端是样式套用即可。
1.单独访问后端,跨域问题。
什么是跨域? 浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域 域名: 主域名不同 www.baidu.com/index.html -->www.sina.com/test.js 子域名不同 www.666.baidu.com/index.html -->www.555.baidu.com/test.js 域名和域名ip www.baidu.com/index.html -->http://180.149.132.47/test.js 端口: www.baidu.com:8080/index.html–… www.baidu.com:8081/test.js 协议: www.baidu.com:8080/index.html–… www.baidu.com:8080/test.js 备注: 1、端口和协议的不同,只能通过后台来解决 2、localhost和127.0.0.1虽然都指向本机,但也属于跨域
其实网上解决跨域的方法一大堆,既然这是前后端分离的搞频发问题,springboot就提供了注解解决这一问题
添加@CrossOrigin(allowCredentials =“true”)
在Controller层上添加@CrossOrigin注解即可
二.SpringBoot 在使用SpringCloud zuul 中解决跨域
这也是坑所在之处,一般项目组调试的时候都是单个服务本地启动,和前端在内网实现调试,但是会有跨域问题,然后理所应当的用了@CrossOrigin注解 这也是坑的地方。 首先zuul配置跨域
2.1.配置yml文件
zuul:
sensitive-headers: Access-Control-Allow-Origin
ignored-headers: Access-Control-Allow-Credentials,Access-Control-Allow-Origin,Vary,X-Frame-Options,token
2.2.添加config文件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @Author: www.fhadmin.org
* @Date: 2019/9/16
* @Description: 使用zuul解决请求跨域问题
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 允许cookies跨域
config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
但是配置完了 ,依然有跨域问题,解决了好久没法解决
问题发现
正常情况下,跨域是这样的:
1. 微服务配置跨域+zuul不配置=有跨域问题
2. 微服务配置+zuul配置=有跨域问题
3. 微服务不配置+zuul不配置=有跨域问题
4. 微服务不配置+zuul配置=ok
问题找到了,走了网管,上面单独服务的跨域配置就要取消了,需要重新把 @CrossOrigin都注释了
问题解决
当然还有一种跨域的解决方案 Access-Control-Allow- 设置 跨域资源共享 CORS 详解
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
HttpServletResponse response = ctx.getResponse();
//解决浏览器跨域问题
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Expose-Headers", "Location");
这是我们项目组的方案 参考 跨域资源共享