1. 程式人生 > >CORS跨域請求405錯誤的另一個坑

CORS跨域請求405錯誤的另一個坑

巨坑:

和同事做聯調(我後端,他前端)解決完跨域請求403錯誤,又冒出來一個405錯誤,查了近一個小時,最後發現是他請求的URL錯了!發現post跨域請求原本404錯誤的,會因為是跨域而報405錯誤,讓人腦袋疼!!!

關於解決CORS跨域請求403錯誤,filter方法:

@Component
public class CorsAllowFilter extends OncePerRequestFilter {

    private static boolean isStaticResources( HttpServletRequest req ) {
        String uri = req.getRequestURI();
        return uri.endsWith(".ico") || uri.endsWith(".html");
    }
    @Override
    protected void doFilterInternal( HttpServletRequest req, HttpServletResponse resp, FilterChain chain ) throws ServletException, IOException {
        if (isStaticResources(req)) {
            chain.doFilter(req, resp);
            return;
        }
        resp.setHeader("Content-type", "application:json;charset=utf8");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "PUT,GET,POST,DELETE,OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "content-type,x-auth");
        chain.doFilter(req, resp);
    }

}