Burton
Burton

Reputation: 447

Postrequest with json, how to access body?

I am trying to understand how to handle post-requests in spring with json-information. But I got a feeling that I have missed something. I guess that I am not supposed to use RequestParam in post request but I dont understand how to access the body-values.

Backend

@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}";
        }

    }

Frontend

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

Upvotes: 0

Views: 108

Answers (1)

Hemant
Hemant

Reputation: 1438

Add RequestBody instead of RequestParam.

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

More @RequestBody Examples

Difference between RequestBody and RequestParam.

Upvotes: 3

Related Questions