【问题标题】:I am using React in frontend and Spring Boot in back end, and I'm getting an error我在前端使用 React,在后端使用 Spring Boot,但出现错误
【发布时间】:2020-08-05 05:48:35
【问题描述】:

这是 Spring Boot 端的代码:

class FruitWrapper{

    List<String> fruits;
  }
class HelloController {
    @PostMapping("/")
    public String hello(@RequestBody FruitWrapper fruits)
     {
        System.out.println(fruits);
    
       return "he";
     }

    }

我正在从这样的反应中发送请求:

 axios.post(`${COURSE_API_URL}`,{"fruits":["apple","orange"]})
.then(resp{console.log(resp.data)})

错误:

 Access to XMLHttpRequest at 'http://localhost:8081/' from origin 'http://localhost:3000'         has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

【问题讨论】:

标签: reactjs spring-boot


【解决方案1】:

这是由于 CORS 来源政策而发生的。您需要在服务器端启用 CORS。通过对控制器方法使用@CrossOrigin 注释来设置 RESTful Web 服务的来源。这个@CrossOrigin 注解支持特定的 REST API,而不是整个应用程序。

@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")

public ResponseEntity<Object> getProduct() {
   return null;
}

全局 CORS 配置

@Bean
public WebMvcConfigurer corsConfigurer() {
   return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/products").allowedOrigins("http://localhost:9000");
      }    
   };
}

来源:https://www.tutorialspoint.com/spring_boot/spring_boot_cors_support.htm

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 2020-11-05
    • 2022-10-18
    • 2021-05-14
    • 2019-06-19
    • 2018-03-15
    • 2019-11-17
    • 2016-11-05
    相关资源
    最近更新 更多