简体   繁体   中英

CORS blocking my backend server, how to fix? Using Springboot java as backend and react js as my front end

import React, { Component } from "react";
import axios from 'axios';

class App extends Component {



  handleSubmit(event) {
    axios.post('http://localhost:3050/login', {
      "username": "username",
      "password": "password"
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    event.preventDefault();
  }

  render() {

      return(

        <form onSubmit={this.handleSubmit}>
          <input type="submit" value="Submit" />
        </form>

      );
  }

}

export default App;

Simply just checks the backend with json of username set to "username" and password set to "password"

My backend is spring boot and using the end link /login with "username" and "Password" should give some response. So this code works except CORS blocks the connection so its stuck on processing forever. A solution I found was disabling all security in chrome and it works. But I'm looking for a permanent solution without having to disable security on chrome settings. Not sure if I do it through springboot or react

Try using the annotation '@CrossOrigin' on your spring REST Endpoint, above the '@RequestMapping' annotation.

eg:-

    @CrossOrigin
    @RequestMapping(value="/login",method=RequestMethod.POST)

When it comes to request POST, you may need additional configs like following;

axio({
  method: 'put',
  headers: {
    'Content-Type': 'application/json',
  },
  data: JSON.stringify({
    "username": "username",
    "password": "password"
  }),
});

Create this bean in u configuration

 @Bean
public CorsConfigurationSource corsConfigurationSource() {

    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of(
            "http://example.net",
            "http://example.com",
           ));
    configuration.setAllowedMethods(ImmutableList.of("HEAD", "OPTIONS", "GET", "POST", "PUT", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(ImmutableList.of("*"));
    configuration.setExposedHeaders(ImmutableList.of("Content-Disposition"));
    configuration.setMaxAge(3600L);

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);

    return source;
}

Please add below file in your project in package where Main spring boot class is present. This worked for me for all CORS issues in Spring boot, React eco system.

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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class CorsWebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
        registry.addMapping("/*.html");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/api/v2/api-docs", "/v2/api-docs");
        registry.addRedirectViewController("/api/swagger-resources/configuration/ui",
                "/swagger-resources/configuration/ui");
        registry.addRedirectViewController("/api/swagger-resources/configuration/security",
                "/swagger-resources/configuration/security");
        registry.addRedirectViewController("/api/swagger-resources", "/swagger-resources");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html**")
                .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
        registry.addResourceHandler("/api/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM