使用 Java 配置的全局 CORS 配置在 Spring MVC 中不起作用

Global CORS configuration using Java Config is not working in Spring MVC

我正在尝试为我在项目中开发的所有 Rest API 在全球范围内启用 CROS,同样我也尝试过这样做 使用 Java 配置的全局 CORS 配置。 以下是带有@Configuration注解的配置class。

package com.fs;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 *
 * @author 
 */
@Configuration
@ComponentScan("com.fs")
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter 
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
           
      registry.addMapping("/**")
          .allowedOrigins("http://localhost:3000")
          .allowedMethods("POST", "GET",  "PUT", "OPTIONS", "DELETE")
          .allowedHeaders("X-Auth-Token", "Content-Type")        
          .maxAge(4800);
    }
}

现在,我正在尝试使用来自 https://localhost:3000 上的 React 应用程序 运行 的 AX 来达到 API 以下,但它没有提供响应并产生网络错误。

从来源 'http://localhost:3000' 访问 'http://localhost:8089/ewamftrxnsws/purchase/getSchemeList' 处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow-Origin' header 出现在请求的资源上。

let requestUrl = "http://localhost:8089/ewamftrxnsws/purchase/getSchemeList";
let promiseResponse = axios.post(requestUrl,{
        headers: {'Content-Type': 'application/json',}
       });
    promiseResponse.then(res=>{
        let isSuccess = res.data;
}).catch( error =>{
        console.log( "MFSchemeListApi catch => "+error);        
    });

有什么问题吗?谢谢

来自:https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

如果您正在使用 Spring 安全性,请确保在 Spring 安全级别启用 CORS,并允许它利用在 Spring MVC 级别定义的配置。

<pre>@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and()... } }

问题可能是因为弃用了“WebMvcConfigurerAdapter”。尝试使用“WebMvcConfigurer”。

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")
                .allowedOrigins(
                        "http://localhost:3000",..)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
                .allowCredentials(true)
        ;
    }

}

这应该将“Access-Control-Allow-Credentials”header带回请求中。

希望这能解决您的问题。试一试吧!!!