spring boot 解决跨域问题
注意:若spring boot启用http://localhost:8081端口 前端请求也应该使用 http://localhost:8081请求
1.使用注解 @CrossOrigin
@RestController
public class TestController {
@GetMapping("/test")
@CrossOrigin
public Test test(){
Test test=new Test();
test.setTest("hhhhh 我被执行了");
return test;
}
}
2.添加CORS过滤器
package com.pzh.vue.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;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter(){
CorsConfiguration corsConfiguration=new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");//源地址
corsConfiguration.addAllowedHeader("*");//头
corsConfiguration.addAllowedMethod("*");//请求方式
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(source);
}
}