0

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);
  };
4
  • 1
    Use @RequestBody instead of @RequestParam to map Body to java object Commented Apr 30, 2020 at 7:01
  • Ok, so i cant access a string directly? Commented Apr 30, 2020 at 7:16
  • never tried but you can try changing content-type to multipart form data Commented Apr 30, 2020 at 7:20
  • RequestParam is used to fetch queryString parameter. Commented May 1, 2020 at 5:53

1 Answer 1

3

Add RequestBody instead of RequestParam.

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

More @RequestBody Examples

Difference between RequestBody and RequestParam.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.