Springboot 2.0.2 - 为PUT和DELETE解析CORS

时间:2018-06-18 02:10:55

标签: java spring-boot cors

我在RestController中使用了@CrossOrigin注释。我的所有GET请求都运行良好。但我正在努力处理PUTDELETE请求。我收到错误:

HttpErrorResponse {headers: HttpHeaders, status: 405, statusText: "OK", url: "http://localhost:8080/api/delete/1", ok: false, …}
  

请注意,我没有对API使用任何身份验证

我的休息控制器(在课程级别上与@CrossOrigin进行了对比):

//Rest Controller

@PutMapping(path = "edit/{id}", produces = MediaType.APPLICATION_JSON_VALUE,
        consumes = MediaType.APPLICATION_JSON_VALUE)
public void editRecipient(@PathVariable("id") Long id,
                          @RequestBody RecipientEntity recipient){
    service.updateRecipient(id, recipient);
}

@DeleteMapping(path = "delete/{id}",  produces = MediaType.APPLICATION_JSON_VALUE)
public void deleteRecipient(@PathVariable("id") Long id) throws NotFoundException {
    service.deleteRecipient(id);
}

这是我的配置文件:

@Configuration
public class WebConfig {

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

2 个答案:

答案 0 :(得分:0)

添加组件CORSFilter

@Component
public class CORSFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, res);
    }

    public void destroy() {
    }

}

在spring config中

@Configuration
public class WebConfig {

    @Autowired
    private CORSFilter corsFilter;

    @Bean
    public FilterRegistrationBean corsFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(corsFilter);
        registration.addUrlPatterns("/*");
        registration.setName("corsFilter");
        registration.setOrder(1);
        return registration;
    }
}

谢谢,

答案 1 :(得分:0)

我已经在控制器中添加了它:

@CrossOrigin(origins = "*", maxAge = 3600L)

我还通过这种方式创建了一个过滤器类:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    /**
     * CORS filter for http-request and response
     */
    public CORSFilter() {
    }

    /**
     * Do Filter on every http-request.
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "access_token, authorization, content-type");

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

    /**
     * Destroy method
     */
    @Override
    public void destroy() {
    }

    /**
     * Initialize CORS filter
     */
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}

现在一切正常!

希望能对您有所帮助!