Spingboot CORS错误仅适用于多部分POST

时间:2018-12-20 06:34:27

标签: spring-boot cors

你好,正面临一个特殊的问题

我已通过以下配置在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);
}

在浏览器上,我看到此请求的选项成功执行,但实际发出了POST,但挂了出去,控制台显示了此错误。

Options call on console

错误是

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​​时,API可以正常工作,所以我认为问题出在CORS配置上,而不是实际的API逻辑

有指针吗?尝试将@CrossOrigin添加到控制器和特定的API没有成功。

2 个答案:

答案 0 :(得分:0)

在配置中添加此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;
}

答案 1 :(得分:0)

我发现了问题。我正在使用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: {}
        });
    }