【问题标题】:How do I prevent a CORS policy error when posting from JS UI to Java API从 JS UI 发布到 Java API 时如何防止 CORS 策略错误
【发布时间】:2022-01-26 02:37:15
【问题描述】:

我的前端应用程序给出了这个错误:

从源“http://localhost:3000”访问“http://localhost:9025/customer/registerDocs/”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查: 它没有 HTTP ok 状态。

何时调用:

updateDocsStatus() {
    return ApiService.postData('http://localhost:9025/customer/registerDocs');
}

这是 API 中的控制器方法:

@PostMapping(value = Constants.REGISTER_DOCS_PATH,
        consumes = {MediaType.APPLICATION_JSON_VALUE},
        produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseStatus(HttpStatus.OK)
public void registerUserForDocs(HttpServletRequest request){
    String username = securityService.getUsername(request);
    customerHelper.registerCustomerForEdocs(username);
}

我不禁觉得问题出在前端。我在这里遗漏了什么明显的东西吗?

【问题讨论】:

  • 你知道 CORS 是如何工作的,特别是客户端和服务器的职责是什么?如果没有,你应该先了解这些。

标签: javascript java rest cors


【解决方案1】:

这是我使用的,可能最好将其与特定的开发配置文件一起使用

@Configuration
public class CorsConfiguration implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**")
            .allowedMethods("*")
            .allowedOrigins("http://localhost:3000")
            .allowedHeaders("*");
}
}

【讨论】:

    【解决方案2】:

    如果您使用 Spring Security,则可以通过添加以下 bean 为所有路径禁用 CORS(不是最佳实践)

    @Configuration
    public class WebConfiguration implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("*");
        }
    }
    

    或者您可以微调到 POST 方法和您的特定文档路径(客户/registerDocs)

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 2019-09-30
      • 2021-12-25
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多