首页 > 解决方案 > 带有json的后请求,如何访问正文?

问题描述

我试图了解如何使用 json 信息在 spring 中处理 post-requests。但我有一种感觉,我错过了一些东西。我想我不应该在发布请求中使用 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);
  };

标签: javascriptjavaspring

解决方案


添加 RequestBody 而不是 RequestParam。

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

更多@RequestBody示例

RequestBody和 RequestParam 之间的区别。


推荐阅读