【问题标题】:CORS error policy in Spring boot and React jsSpring boot 和 React js 中的 CORS 错误策略
【发布时间】:2021-08-14 09:53:36
【问题描述】:

我使用 React JS 作为前端,Spring boot 作为后端服务。 使用Axios 调用删除服务时出现CORS 错误。在 Rest 控制器类中添加了跨域。

@CrossOrigin(origins = {"http://localhost:3000/"}

谁能帮助解决这个 CORS 问题?

**Error message: Access to XMLHttpRequest at 'http://localhost:8080/testdelete' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.**

我的 ReactJS 代码:

return axios({
    method:'DELETE',
    url:`http://localhost:8080/testdelete`,
    data: data,
    headers: {
        'Access-Control-Allow-Headers':'Content-Type',
        'Access-Control-Allow-Origin': 'http://localhost:3000',
        'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
        'Content-Type': 'application/json'
    }
}) 

这是我的 Spring 启动控制器代码:

@CrossOrigin(origins = {"http://localhost:3000/"},
methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.POST,RequestMethod.OPTIONS})

@RestController
public class TestDelete {
    @DeleteMapping("/testdelete")   
    public ResponseEntity<void> deleteData(@RequestBody Data data) throws Exception {
        // logic
    }
}

【问题讨论】:

  • 请同时添加代码sn-ps。
  • 添加代码 sn-p.
  • 尝试 @CrossOrigin(origins = {"localhost:3000"}) 代替 @CrossOrigin(origins = {"localhost:3000"}) (不带 / )
  • @Rebai Ahmed - 删除了 '/',放置了 @CrossOrigin(origins = {"localhost:3000"}) 但仍然无法正常工作。
  • 检查我的答案,希望对您有所帮助!

标签: reactjs spring-boot cors


【解决方案1】:

尝试为你的 spring-boot 项目添加 cors 配置:

@Configuration
public class MyConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*");
    }

}

【讨论】:

  • 所有方法都运行良好,但 DELETE 方法出现 CORS 策略错误。是否有任何其他明确的 DELETE 方法配置。
  • 其他方法实现和DELETE方法有什么区别?
猜你喜欢
  • 2021-11-14
  • 2020-05-03
  • 2020-07-05
  • 2019-11-07
  • 2021-01-23
  • 2021-04-19
  • 2021-12-19
  • 2020-06-03
  • 2020-05-02
相关资源
最近更新 更多