【问题标题】:how to make post request by axios with multiple parameters in Reactjs如何通过 axios 在 Reactjs 中使用多个参数发出 post 请求
【发布时间】:2020-02-25 13:02:43
【问题描述】:

我的 Springboot 后端休息 API 需要一个带有 2 个参数的 POST 请求,如下所示:-

    @PostMapping(path = "/profile" , consumes = {"multipart/form-data"})
public ResponseEntity<?> addOrUpdateProfile(@RequestPart("profile") Profile profile,  @RequestParam("file") MultipartFile file) {
    System.out.println("file name:"+file.getOriginalFilename()+" file is here. Save it");
    profileService.saveOrUpdateExpense(profile);
    return new ResponseEntity<>("Expense added succcessfully", HttpStatus.OK);
}

我可以通过 curl 测试后端代码为:-

curl -X POST -H 'Content-Type: multipart/form-data'  -F profile='{ "displayName": "ma ma",  "birthDate": "1999-01-01", "gender": "male"};type=application/json' -F file=@'/home/dev/Downloads/file.pdf;type=application/octet-stream'   http://localhost:8080/profile

现在我试图在我的反应前端通过 axios 发出相同的 POST 请求。我是 ReactJs 的新手,我不知道该怎么做。请让我知道该怎么做?

【问题讨论】:

    标签: reactjs post axios


    【解决方案1】:

    像这样你可以使用带有多个参数的 axios 的 post 并将 Content-Type 标头设置为文件的 multipart/form-data

      var formData = new FormData();
        formData.append("file", '/home/dev/Downloads/file.pdf');
        formData.append("data", {"displayName": "ma ma",  "birthDate": "1999-01-01", "gender": "male"});
        axios.post('http://localhost:8080/profile', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
        })
    

    【讨论】:

    • 但我在请求中也需要该文件。我只能做一个参数没有任何问题。您可能没有注意到请求的结束。 -F file=@'/home/dev/Downloads/file.pdf;type=application/octet-stream'
    • 当我发布错误代码 415。这意味着不受支持的媒体类型。
    猜你喜欢
    • 2018-04-25
    • 2018-06-16
    • 2020-12-04
    • 2022-11-02
    • 1970-01-01
    • 2021-05-07
    • 2019-03-05
    • 2020-11-07
    • 2021-12-25
    相关资源
    最近更新 更多