MyBatis+SpringMVC+SpringBootSpringboot核心技术SpringBoot极简教程 · Spring Boot

SpringBoot下OPTIONS方法返回401错误

2018-07-06  本文已影响1人  褪色的记忆1994

设置跨域和放行OPTIONS方法

@Component
public class CorsFilter implements Filter {

@Override
public void init(FilterConfig fc) throws ServletException {
}

@Override
public void doFilter(ServletRequest req, ServletResponse resp,
        FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) resp;
    HttpServletRequest request = (HttpServletRequest) req;
    response.setHeader("Access-Control-Allow-Origin", "*");
    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, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, resp);
    }

}

@Override
public void destroy() {
}

}
上一篇下一篇

猜你喜欢

热点阅读