spring boot跨域设置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot跨域设置相关的知识,希望对你有一定的参考价值。
参考技术A方式一
在需要跨域的整个Controller或者单个方法上添加@CrossOrigin注解
方式二(全局配置)
方式三(通过filter)
@Component
@WebFilter(urlPatterns = "/*", filterName = "authFilter") //这里的“/*” 表示的是需要拦截的请求路径
public class PassHttpFilter implements Filter
@Override
public void init(FilterConfig filterConfig) throws ServletException
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
httpResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
filterChain.doFilter(servletRequest, httpResponse);
@Override
public void destroy()
学习java类知识,推荐来北京尚学堂,多年java教育培训经验,有着先进的知识储备和优秀的师资力量,会让你在java学习中快人一步。
Spring Boot2.1.3全局跨域
/**
* 配置跨域访问
*
* @author Terwer
*/
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")
.maxAge(3600);
}
};
}
以上是关于spring boot跨域设置的主要内容,如果未能解决你的问题,请参考以下文章