本文介绍了Java Spring REST API CORS不适用于通过jQuery与Chrome的DELETE请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个使用jQuery编写的Web前端,它使用Spring框架将REST请求发送到用Java编写的REST Web服务。我在CORS请求中遇到了一个奇怪的错误。特别是,如果我使用Safari,一切正常;相反,使用Chrome,所有DELETE请求都会失败(GET和POST请求在Chrome中也能正常工作)。

I'm creating a web fronted written using jQuery which sends REST request to a REST Web Service written in Java using Spring framework. I'm facing a weird error with CORS requests. In particular, everything works fine if I use Safari; instead, with Chrome all DELETE requests fail (both GET and POST requests work fine in Chrome too).

我得到的错误是:

Response to preflight request doesn't pass access control check: No 
'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'null' is therefore not allowed access. 
The response had HTTP status code 403.

发出第一个OPTIONS请求时会发生这种情况通过Chrome。

This happens when a first OPTIONS request is issued by Chrome.

我的CORS代码是:

@Configuration
@EnableWebMvc
public class CorsConfigurator extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS");
    }
}

@SpringBootApplication
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new CorsConfigurator();
    }

}

我还尝试添加 @CrossOrigin 对我的 @RestController 的注释,但没有任何改变。有人知道要解决这个问题吗?

I also tried to add the @CrossOrigin annotations to my @RestController but nothing changed. Does somebody know ho to fix this?

谢谢你,
Marco

Thank you,Marco

推荐答案

我在Spring启动应用程序中遇到此错误,我通过添加或启用cors功能解决了这个问题,如下所示

I got this error in spring boot application and I resolved it by adding or enabling cors features as below

cors:
allowed-origin :
allowed-methods:
allowed-headers:

exposed-headers:授权,链接,X-Total-Count
allow-credentials:true
max-age:1800

cors: allowed-origins: "http://localhost:8082" allowed-methods: "" allowed-headers: "" exposed-headers: "Authorization,Link,X-Total-Count" allow-credentials: true max-age: 1800

这篇关于Java Spring REST API CORS不适用于通过jQuery与Chrome的DELETE请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 02:44