Spingboot CORS错误仅适用于Multipart POST [英] Spingboot CORS error only for Multipart POST

查看:97
本文介绍了Spingboot CORS错误仅适用于Multipart POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hello am facing a peculiar issue

我已经在Springboot API Server上启用了具有以下配置的CORS

I have enabled CORS on my Springboot API Server with following configuration

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

我的所有POST请求都可以正常工作,除了用于上传图片的API。其实现为

All my POST requests are working except an API for image upload. Its implemented as

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

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

On browser I see the OPTION for this request succeeding but the actual POST being made but hanging out and the console the displaying this error.

错误是

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]

使用该API后,API可以正常工作来自PostMan,所以我认为问题出在CORS配置上,而不是实际的API逻辑

The API does works correctly when used from PostMan so I think the issue is with CORS configuration and not actual API logic

任何指针吗?尝试将@CrossOrigin添加到控制器和特定的API均未成功。

Any pointers? Have tried adding @CrossOrigin to controller and specific API without any success.

推荐答案

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

I found the issue. I am using angular 7 and angular http component. Had to change my post method from

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: {}
        });
    }

这篇关于Spingboot CORS错误仅适用于Multipart POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆