V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
liubx
V2EX  ›  Java

碰到了跨域问题, Redirect is not allowed for a preflight request

  •  
  •   liubx · 2020-09-07 15:48:23 +08:00 · 4373 次点击
    这是一个创建于 1324 天前的主题,其中的信息可能已经有所发展或是发生改变。
    • 后端配置:
    @Configuration
    public class CorsConfigure implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                    .allowCredentials(true)
                    .maxAge(3600)
                    .allowedHeaders("*");
        }
    }
    
    
    • 然后前端的 OPTIONS 预请求有 302 问题。后台添加拦截器放行所有的 OPTIONS 方法
    @Component
    public class CorsInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
            response.setHeader("Access-Control-Max-Age", "86400");
            response.setHeader("Access-Control-Allow-Headers", "*");
    
            // 如果是 OPTIONS 则结束请求
            if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
                response.setStatus(HttpStatus.NO_CONTENT.value());
                return false;
            }
            return true;
        }
    }
    
    • 但是这个 OPTIONS 没有挟带 cookie,被 shiro 框架拦截了。请问是因为 OPTIONS 方法没有挟带 cookie 导致的吗? 后台还需不需要做什么处理?
    3 条回复    2020-09-07 19:15:06 +08:00
    treblex
        1
    treblex  
       2020-09-07 18:05:48 +08:00
    allowCredentials 为 true 的时候需要具体域名,不能使用*匹配,看下是不是这个
    treblex
        2
    treblex  
       2020-09-07 18:07:40 +08:00
    @suke971219 #1 options 请求应该返回 204 的
    liubx
        3
    liubx  
    OP
       2020-09-07 19:15:06 +08:00
    @suke971219 谢谢。
    现在找到原因了。是 shiro 把 options 拦截了。因为 options 没有挟带 cookie 。现在让 shiro 不拦截 options 就好了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3317 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:49 · PVG 21:49 · LAX 06:49 · JFK 09:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.