React JS и Spring boot CORS POLICY - PullRequest
0 голосов
/ 24 марта 2020

всем привет, я пытаюсь сделать мой первый полный пакет приложения с пружинной загрузкой и React js, но я решаю некоторую проблему CORS-ошибка при подключении локального интерфейса React к локальному приложению промежуточного ПО Spring Boot

, поэтому аннотации :

 @Controller
@RequestMapping("/regions")
@RestController
@CrossOrigin()

classe WebSecurityConfig:

> package sales.reporting.atos.BackEndPFE.config;
>        import java.util.Arrays;
> 
> import org.springframework.context.annotation.Bean; import
> org.springframework.security.config.annotation.web.builders.HttpSecurity;
> import
> org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
> import
> org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
> import org.springframework.web.cors.CorsConfiguration; import
> org.springframework.web.cors.CorsConfigurationSource; import
> org.springframework.web.cors.UrlBasedCorsConfigurationSource;
> 
> @EnableWebSecurity
>     public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
>     @Override
>     protected void configure(HttpSecurity http) throws Exception {
>         http.cors().and();
>             //other configurations that you want
>     }
>     
>     @Bean
>     CorsConfigurationSource corsConfigurationSource()
>     {
>         CorsConfiguration configuration = new CorsConfiguration();
>         configuration.setAllowedOrigins(Arrays.asList("*"));
>         //or any domain that you want to restrict to 
>         configuration.setAllowedMethods(Arrays.asList("GET","POST"));
>         //Add the method support as you like
>         UrlBasedCorsConfigurationSource source = new     UrlBasedCorsConfigurationSource();
>         source.registerCorsConfiguration("/**", configuration);
>         return source;
>     } }

мой топор ios:

       import axios from 'axios'; export const Majregions = (Majregion , history) => async dispatch => {

await axios.post("http://localhost:8080/regions/add" , Majregion);
history.push("/regions/add")

}

проблемы:

   xhr.js:178 POST http://localhost:8080/regions/add net::ERR_CONNECTION_REFUSED
    dispatchXhrRequest @ xhr.js:178
    xhrAdapter @ xhr.js:12
    dispatchRequest @ dispatchRequest.js:52
    Promise.then (async)
    request @ Axios.js:61
    Axios.<computed> @ Axios.js:86
    wrap @ bind.js:9
    (anonymous) @ AtosAction.js:4
    (anonymous) @ index.js:8
    (anonymous) @ redux.js:477
    onSubmit @ Majregion.js:40
    callCallback @ react-dom.development.js:188
    invokeGuardedCallbackDev @ react-dom.development.js:237
    invokeGuardedCallback @ react-dom.development.js:292
    invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
    executeDispatch @ react-dom.development.js:389
    executeDispatchesInOrder @ react-dom.development.js:414
    executeDispatchesAndRelease @ react-dom.development.js:3278
    executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
    forEachAccumulated @ react-dom.development.js:3259
    runEventsInBatch @ react-dom.development.js:3304
    runExtractedPluginEventsInBatch @ react-dom.development.js:3514
    handleTopLevel @ react-dom.development.js:3558
    batchedEventUpdates$1 @ react-dom.development.js:21902
    batchedEventUpdates @ react-dom.development.js:1060
    dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
    attemptToDispatchEvent @ react-dom.development.js:4267
    dispatchEvent @ react-dom.development.js:4189
    unstable_runWithPriority @ scheduler.development.js:653
    runWithPriority$1 @ react-dom.development.js:11061
    discreteUpdates$1 @ react-dom.development.js:21918
    discreteUpdates @ react-dom.development.js:1071
    dispatchDiscreteEvent @ react-dom.development.js:4168
    createError.js:16 Uncaught (in promise) Error: Network Error
        at createError (createError.js:16)
        at XMLHttpRequest.handleError (xhr.js:83)

Что мне нужно сделать, мне нужно исправить эту ошибку, мне нужно сохранить форму данных, но я уже получаю эту ошибку

1 Ответ

0 голосов
/ 24 апреля 2020

Поместите следующий код в ваш класс, где присутствует метод main.и удалите ваш класс WebSecurityConfig

 @Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "PATCH")
                    .allowCredentials(true);
        }
    };
}
...