-1
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

ss sss
  • 75
  • 7
  • Begin from [this](https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control) – hindmost Oct 09 '19 at 16:39
  • Here is the answer [How to overcome the CORS issue in ReactJS](https://stackoverflow.com/questions/43462367/how-to-overcome-the-cors-issue-in-reactjs) – luizfvm Oct 09 '19 at 16:52

4 Answers4

4

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

eg:-

    @CrossOrigin
    @RequestMapping(value="/login",method=RequestMethod.POST)
Harry Manoharan
  • 181
  • 1
  • 12
0

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"
  }),
});
Misol Goh
  • 813
  • 6
  • 9
0

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

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