【问题标题】:Spingboot CORS error only for Multipart POSTSpring Boot CORS 错误仅适用于 Multipart POST
【发布时间】:2019-05-20 16:06:46
【问题描述】:

您好,我遇到了一个特殊的问题

我在 Springboot API 服务器上启用了 CORS,配置如下

@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
}

我所有的 POST 请求都在工作,除了一个用于图像上传的 API。其实现为

@PostMapping(value = "/profiles/{id}/image")
@ResponseStatus(value = HttpStatus.CREATED)
public void uploadProfileImage(@PathVariable Long id, @RequestPart MultipartFile file) {
    this.userService.uploadProfileImage(id, file);
}

在浏览器上,我看到此请求的 OPTION 成功,但实际 POST 正在进行但挂起,控制台显示此错误。

错误是

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:10000/users/profiles/1/image. (Reason: CORS request did not succeed).[Learn More]

从 PostMan 使用时,API 确实可以正常工作,所以我认为问题在于 CORS 配置而不是实际的 API 逻辑

有什么建议吗?已尝试将 @CrossOrigin 添加到控制器和特定 API,但没有成功。

【问题讨论】:

    标签: spring-boot cors


    【解决方案1】:

    在您的配置中添加此 bean 以支持 CORS:

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("Access- Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method", "Access-Control-Request-Headers","Origin","Cache-Control", "Content-Type", "Authorization"));
        configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    

    【讨论】:

      【解决方案2】:

      我发现了问题。我正在使用 angular 7 和 angular http 组件。不得不从

      更改我的发布方法
      uploadImageFile(file: File, id: number) {
              const formData: FormData = new FormData();
              formData.append('file', file, file.name);
              return this.http.post(`${environment.apiEndpoint}/users/profiles/${id}/image`, formData);
          }
      

      uploadImageFile(file: File, id: number) {
              const formData: FormData = new FormData();
              formData.append('file', file, file.name);
              return this.http.post(`${environment.apiEndpoint}/users/profiles/${id}/image`, formData, {
                  // This is required to manage post multipart updates
                  headers: {}
              });
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-22
        • 2020-11-19
        • 1970-01-01
        • 2018-03-09
        • 2021-11-09
        • 2021-05-29
        • 2020-06-02
        • 1970-01-01
        相关资源
        最近更新 更多