首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spingboot CORS错误仅适用于多部分POST

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

Stack Overflow用户
提问于 2018-12-20 14:34:27
回答 2查看 2.3K关注 0票数 0

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

我已经使用以下配置在Springboot API服务器上启用了CORS

代码语言:javascript
复制
@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
}

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

代码语言:javascript
复制
@PostMapping(value = "/profiles/{id}/image")
@ResponseStatus(value = HttpStatus.CREATED)
public void uploadProfileImage(@PathVariable Long id, @RequestPart MultipartFile file) {
    this.userService.uploadProfileImage(id, file);
}

在浏览器上,我看到此请求成功的选项,但实际的POST已完成但挂起,而控制台显示此错误。

错误是

代码语言:javascript
复制
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中,但没有成功。

EN

回答 2

Stack Overflow用户

发布于 2018-12-20 15:00:48

我找到问题了。我使用的是angular 7和angular http组件。我不得不将我的post方法从

代码语言:javascript
复制
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);
    }

代码语言:javascript
复制
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: {}
        });
    }
票数 2
EN

Stack Overflow用户

发布于 2018-12-20 14:40:29

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

代码语言:javascript
复制
@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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53863529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档