当我们练习前后端分离的项目时经常会到跨域的问题,报错信息如下: Access to XMLHttpRequest at ‘http://127.0.0.1/books’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
发生跨域的原因这里就不做阐述了,直接在后端进行处理吧!
网上的解决方案很多,以下是我常用的方法:
1、方案1:方法或者类上标注@CrossOrigin注解
@RestController
@RequestMapping("/books")
//解决跨域问题
@CrossOrigin(origins = "*")//直接使用也可以:@CrossOrigin
public class UserController {
//自动装配
@Autowired
private iNewsUser newsUserImlp;
//查询全部
@GetMapping
public Object seleAll(){
return newsUserImlp.seleAll();
}
}
2、使用拦截器的方式
//处理跨域的Filter
//1. 添加 CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//放行哪些原始域
config.addAllowedOrigin("*");
//是否发送 Cookie
config.setAllowCredentials(false);
//放行哪些请求方式
config.addAllowedMethod("*");
//放行哪些原始请求头部信息
config.addAllowedHeader("*");
//暴露哪些头部信息
config.addExposedHeader("*");
//2. 添加映射路径
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**",config);
完美解决!