使用vue+axios+spring boot前后端分离项目时会出现跨域问题
解决方式:
一: 全局配置
1 /** 2 * 就是注册的过程,注册Cors协议的内容。 3 * 如: Cors协议支持哪些请求URL,支持哪些请求类型,请求时处理的超时时长是什么等。 4 */ 5 @Override 6 public void addCorsMappings(CorsRegistry registry) { 7 registry 8 .addMapping("/**")// 所有的当前站点的请求地址,都支持跨域访问。 9 .allowedMethods("GET", "POST", "PUT", "DELETE") // 当前站点支持的跨域请求类型是什么。 10 .allowCredentials(true) // 是否支持跨域用户凭证 11 .allowedOrigins("*") // 所有的外部域都可跨域访问。 如果是localhost则很难配置,因为在跨域请求的时候,外部域的解析可能是localhost、127.0.0.1、主机名 12 .maxAge(60); // 超时时长设置为1小时。 时间单位是秒。 13 }
二: 针对单个接口,使用注解@CrossOrigin
1 /** 2 * @desc 3 * @author guozhongyao 4 * @date 2020/03/22 17:05 5 */ 6 @RestController 7 @RequestMapping("/user") 8 @RequiredArgsConstructor 9 @CrossOrigin(origins = "*",maxAge = 3600) 10 public class UserController { 11 12 final UserMapper userMapper; 13 14 @GetMapping("/getOne/{id}") 15 public User getOne(@PathVariable("id") Integer id) { 16 return userMapper.getById(id); 17 } 18 }
三: 自定义跨域过滤器
1,编写过滤器
public class CrosFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletResponse res = (HttpServletResponse) response; HttpServletRequest req = (HttpServletRequest) request; String origin = req.getHeader("Origin"); if (!org.springframework.util.StringUtils.isEmpty(origin)) { //带cookie的时候,origin必须是全匹配,不能使用* res.addHeader("Access-Control-Allow-Origin", origin); } res.addHeader("Access-Control-Allow-Methods", "*"); String headers = req.getHeader("Access-Control-Request-Headers"); // 支持所有自定义头 if (!org.springframework.util.StringUtils.isEmpty(headers)) { res.addHeader("Access-Control-Allow-Headers", headers); } res.addHeader("Access-Control-Max-Age", "3600"); // enable cookie res.addHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(request, response); } @Override public void destroy() { // TODO Auto-generated method stub } }
2, 注册过滤器
1 /** 2 * @desc 注册自定义跨域过滤器 3 * @author guozhongyao 4 * @date 2020/3/30 15:52 5 */ 6 @Bean 7 public FilterRegistrationBean registerFilter(){ 8 FilterRegistrationBean bean = new FilterRegistrationBean(); 9 bean.addUrlPatterns("/*"); 10 bean.setFilter(new CrosFilter()); 11 return bean; 12 }
四: 使用nginx反向代理服务器解决跨域问题
1, 在nginx的conf目录下,创建vhosts文件夹
2, 在nginx.conf 文件中添加 include vhosts/*.conf;
3, vhost目录下创建 abc.conf文件