【问题标题】:CORS blocking my backend server, how to fix? Using Springboot java as backend and react js as my front endCORS 阻止了我的后端服务器,如何解决?使用 Springboot java 作为后端, react js 作为我的前端
【发布时间】:2020-02-07 01:17:48
【问题描述】:
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;

只需检查后端的用户名设置为“用户名”和密码设置为“密码”的 json

我的后端是 spring boot,使用带有“用户名”和“密码”的结束链接 /login 应该会给出一些响应。因此,此代码有效,但 CORS 阻止了连接,因此它永远卡在处理中。我发现的一个解决方案是禁用 chrome 中的所有安全性,它可以工作。但我正在寻找一个永久的解决方案,而不必禁用 chrome 设置的安全性。不知道我是通过springboot还是react

【问题讨论】:

标签: javascript java reactjs spring-boot cors


【解决方案1】:

尝试在 Spring REST Endpoint 上的“@RequestMapping”注释上方使用注释“@CrossOrigin”。

例如:-

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

【讨论】:

    【解决方案2】:

    当涉及到请求 POST 时,您可能需要额外的配置,如下所示;

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

    【讨论】:

      【解决方案3】:

      在你的配置中创建这个bean

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

      【讨论】:

        【解决方案4】:

        请在您的项目中添加以下文件,该文件位于主 spring boot 类所在的包中。这对我在 Spring boot 和 React 生态系统中的所有 CORS 问题都有效。

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

        【讨论】:

          猜你喜欢
          • 2018-06-26
          • 2018-07-21
          • 2019-08-05
          • 1970-01-01
          • 2018-05-04
          • 1970-01-01
          • 1970-01-01
          • 2021-10-01
          • 2019-09-04
          相关资源
          最近更新 更多