【问题标题】:React JS send post request to Springboot Rest Server and get errorReact JS 向 Springboot Rest Server 发送 post 请求并得到错误
【发布时间】:2021-07-15 05:34:58
【问题描述】:

我将我的 React 应用程序托管在 localhost:3000,并将我的 SpringBoot RESTServer 托管在 localhost:8080,尝试向该服务器发送一个发布请求并收到以下错误: 从源“http://localhost:3000”访问“http://localhost:8080/employees”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在 Access-Control-Allow-Origin' 标头。

但我已经将 Access-Control-Allow-Origin 放入我的代码中:

axios.post('http://localhost:8080/employees', params, {
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
        'mode': 'no-cors'
      }
    }
    )

API 用 postman 测试过,它工作正常。 请帮帮我。

【问题讨论】:

    标签: reactjs spring-boot post axios cors


    【解决方案1】:

    这是由CORS 问题引起的。你可以google它并获得很多解释,这些解释会告诉你为什么当你通过浏览器调用api时请求被阻止。

    基本上,Access-Control-Allow-OriginCORS 问题可以通过设置您的 api 端点来解决。对于sprint-boot api,你可以试试这两种方式。

    1. @CrossOrigin添加到特定路径控制器
    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/employees")
    public Employees getEmployees() {
        // ...
    }
    
    1. 设置全局CORS配置
    @Configuration
    public class MyConfiguration {
    
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    // Allow all origin to call your api
                    registry.addMapping("/**");
                }
            };
        }
    }
    

    您可以参考this article 更清楚地了解spring-boot 中的CORS 设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2021-05-08
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 2020-10-05
      相关资源
      最近更新 更多