Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

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

I am trying to enbale CROS globally for all the my Rest API developed in project and for the same i have tried doing the same with Global CORS configuration using Java Config. Following is the configuration class with @Configuration annotation.

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);
    }
}

Now , i am trying to hit below API using AX from react application running on https://localhost:3000 , but it's not providing Response and producing Network Error.

Access to XMLHttpRequest at 'http://localhost:8089/ewamftrxnsws/purchase/getSchemeList' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

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);        
    });

What is the problem ? Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

If you are using Spring Security, make sure to enable CORS at Spring Security level as well to allow it to leverage the configuration defined at Spring MVC level.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...