Spring CORS No 'Access-Control-Allow-Origin' header is present

后端 未结 11 1211
半阙折子戏
半阙折子戏 2020-11-30 18:21

I am getting the following problem after porting web.xml to java config

No \'Access-Control-Allow-Origin\' header is present on the requested resource. Origi         


        
11条回答
  •  猫巷女王i
    2020-11-30 19:00

    For some reason, if still somebody not able to bypass CORS, write the header which browser wants to access your request.

    Add this bean inside your configuration file.

    @Bean
    public WebSecurityConfigurerAdapter webSecurity() {
        return new WebSecurityConfigurerAdapter() {
    
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.headers().addHeaderWriter(
                        new StaticHeadersWriter("Access-Control-Allow-Origin", "*"));
    
    
            }
        };
    }
    

    This way we can tell the browser we are allowing cross-origin from all origin. if you want to restrict from specific path then change the "*" to {'http://localhost:3000',""}.

    Helpfull reference to understand this behaviour https://www.concretepage.com/spring-4/spring-4-rest-cors-integration-using-crossorigin-annotation-xml-filter-example

提交回复
热议问题