【问题标题】:Postrequest with json, how to access body?使用 json 发布请求,如何访问正文?
【发布时间】:2020-08-14 11:18:28
【问题描述】:

我正在尝试了解如何在春季使用 json 信息处理后期请求。但我有一种感觉,我错过了一些东西。我想我不应该在发布请求中使用 RequestParam,但我不明白如何访问正文值。

后台

@CrossOrigin(origins = "http://localhost:3000")
    @PostMapping(path = "api/delete", consumes = "application/json", produces = "application/json")
    @ResponseBody
    public String delete(@RequestParam("filename") String filename) throws IOException {

        String filePath = imageFolder + filename;
        File file = new File(filePath);
        logger.info(filePath);

        if(file.delete())
        {
            return "{\"success\":1}";
        }
        else
        {
            return "{\"fail\":1}";
        }

    }

前端

const deleteImage = () => {
    const re = /images\/(.+)$/;
    const filePath = imageUrl.match(re);
    const url = `http://localhost:8080/api/delete/`

    const data = {filename:filePath}

    const options = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: data
    };

    fetch(url, options);
  };

【问题讨论】:

  • 使用@RequestBody而不是@RequestParam将Body映射到java对象
  • 好的,所以我不能直接访问字符串?
  • 从未尝试过,但您可以尝试将内容类型更改为多部分表单数据
  • RequestParam 用于获取 queryString 参数。

标签: javascript java spring


【解决方案1】:

添加 RequestBody 而不是 RequestParam。

public String delete(@RequestBody String filename) throws IOException {}

更多@RequestBody例子

Difference 在 RequestBody 和 RequestParam 之间。

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 2021-07-06
    • 2017-02-12
    • 2019-04-19
    • 2015-03-20
    • 2023-04-10
    • 2011-07-02
    • 2018-08-18
    相关资源
    最近更新 更多