两种方法从SpringBoot的方向解决跨域问题
今天搭建博客的时候,尝试性的传递数据,发现浏览器报了这个错误
…blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
也就是跨域请求的错误,
首先 在运行过程中,通过各种测试,发现前端的设置并不影响跨域,只要后端配置了允许跨域就能进行跨域请求
解决跨域,SpringBoot2.x版本
这次知道了有些问题,直接在Spring官网搜索,好像要方便些
Spring官方关于配置跨域的引导
SpringBoot2.x版本对跨域的支持有了更好的完善
参考文档我们能知道两种方法设置跨域
- Controller method CORS configuration(基于Controller的跨域配置)
- Global CORS configuration(全局跨域配置)
基于Controller的跨域配置
使用@CrossOrigin注解,我们先码一下官方介绍
@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
This @CrossOrigin annotation enables cross-origin requests only for this specific method.
By default, its allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation and a maxAge of 30 minutes is used. You can customize this behavior by specifying the value of one of the annotation attributes: origins, methods, allowedHeaders, exposedHeaders, allowCredentials or maxAge. In this example, we only allow http://localhost:9000 to send cross-origin requests.
上面叽叽喳喳大致意思是,用@CrossOrigin注解在@Controller类上就能打开跨域,默认允许所有的访问,如果要定制的话,加属性即可,有
- origins(允许跨域请求的域名),
- methods(方法),
- allowedHeaders
- exposedHeaders
- allowCredentials
- maxAge(跨域允许的时间)
全局跨域配置
全局跨域配置使用的是SpringBoot的配置,重写WebMvcConfiger中的addCorsMappings方法,用Bean的方法注入即可达到开启多个跨域的效果,更多的配置,类似上面的6条,直接添加即可
下面是原文:
As an alternative to fine-grained annotation-based configuration, you can also define some global CORS configuration as well. This is similar to using a Filter based solution, but can be declared within Spring MVC and combined with fine-grained @CrossOrigin configuration. By default all origins and GET, HEAD and POST methods are allowed.
src/main/java/hello/GreetingController.java
@GetMapping("/greeting-javaconfig")
public Greeting greetingWithJavaconfig(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
src/main/java/hello/Application.java
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig")
.allowedOrigins("http://localhost:9000");
}
};
}
You can easily change any properties (like the allowedOrigins one in the example), as well as only apply this CORS configuration to a specific path pattern. Global and controller level CORS configurations can also be combined.
除了上面这种添加Bean的配置方式,我们也可以用实现接口的方法来实现
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
.allowedOrigins("*")
//是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
效果是相同的,完全可行