参考地址:https://blog.csdn.net/fxbin123/article/details/80603678
/**
* 通过这种方式以确保所有接口的response header都能够设置相应参数,以解决本地调试跨域问题
* ModelAttribute注解只对当前controller有效
* @param response
*/
@ModelAttribute
public void setVaryResponseHeader(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
response.setHeader("Access-Control-Allow-Credentials","true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
}
配置拦截器:
@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedOrigins("*")
.allowedMethods("*");
}
}