后端解决请求跨域问题

在拦截器里直接设置request请求的 header

    public ContainerResponse filter(ContainerRequest creq, ContainerResponse cres) {
        cres.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
        // 允许的Header值,不支持通配符
        cres.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        cres.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
        // 即使只用其中几种,header和options是不能删除的,因为浏览器通过options请求来获取服务的跨域策略
        cres.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        // CORS策略的缓存时间
        cres.getHttpHeaders().add("Access-Control-Max-Age", "1209600");
        // 可以通过 throw new WebApplicationException(Status.UNAUTHORIZED); 来中断请求
        return cres;
    }

 

posted @ 2022-11-11 16:30  下课后我要去放牛  阅读(109)  评论(0)    收藏  举报