'How do I get the return statement from JavaScript's Fetch?

Now I'm using Fetch to fetch some data from an API in SpringBoot.

const onSubmit = (data) => {
    fetch("http://localhost:8080/addMedicine", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });
  };

Here is the Java code.

 @PostMapping("/addMedicine")
    public String addMedicine (@RequestBody Medicine medicine){
        return medicineService.addMedicine(medicine);
    }

 public String addMedicine(Medicine medicine) {
        medicineRepository.save(medicine);
        System.out.println("Added medicine "+ medicine.getMedicineName());
        return "Added medicine "+ medicine.getMedicineName() ;
    }

The above methods are from different classes I just put them here to simplify my question.

Now when I use Postman I get the statement like "Added medicine X"

Now when I post the data from my Frontend app which is in React. I want to get that statement so that I can use it to display something on the page as a confirmation.

How am I going to do it or for more info how does even Postman do it because it looks so easy from them? Please help.



Solution 1:[1]

this should work :

const onSubmit = (data) => {
    fetch("http://localhost:8080/addMedicine", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }).then(data=>{


      // Do something ....


    })
  };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Khalfoun Mohamed El Mehdi