Search code examples
javascriptjsonspringspring-bootspring-restcontroller

Fetching JSON data from @RestContoller using JavaScript


Why the html page doesn't load on specific requested URL and doesn't fetching data from JSON format? Result of opening api/reservations/all

Controller:

@RestController
@RequestMapping("api/reservations")
public class ReservationController {

    private final ReservationService reservationService;

    @Autowired
    public ReservationController(ReservationService reservationService) {
        this.reservationService = reservationService;
    }
 @GetMapping("/all")
    public List<Reservation> showAllReservations() throws SQLException {
        return reservationService.showAllReservations();
    }
}

HTML + Javascript

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Reservations</title>
  </head>
  <body>
    <script>
      // Fetch JSON data from REST controller
      fetch("http://localhost:8080/api/reservations/all")
        .then((response) => response.json())
        .then((data) => {
          // Iterate over each object in the JSON array
          var formattedData = "";

          data.forEach((item) => {
            formattedData +=
              "<p>Reservation ID: " +
              item.id +
              "</p>" +
              "<p>Customer: " +
              item.customer.name +
              "</p>" +
              "<p>Email: " +
              item.customer.email +
              "</p>" +
              "<p>Check-in Date: " +
              item.dateCheckIn +
              "</p>" +
              "<p>Check-out Date: " +
              item.dateCheckOut +
              "</p>" +
              "<hr>"; 
          });
          // Update the HTML container with the formatted data
          var dataContainer = document.getElementById("data-container");
          dataContainer.innerHTML = formattedData;
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    </script>
    <div id="data-container"></div>
  </body>
</html>

I checked URL correctness, controller seems fine, the files locates in different folders (templates for .html and src>java>package for controller).


Solution

  • The problem was inattention, clicking on the button took me to api/reservation/all instead of reservations.html and so the javascript didn't work and didn't show the result. Thanks for your answers.