javaspringaxiosfetch

400 error when Sending an axios post request to Spring backend


I have this data that I want to send over to a backend endpoint to perform some database operations, now the issue is when I check the network, I can see that request does get initiated and does contain the data as it's request body, but somehow it tells me that it the endpoint didn't recieve a parametre when it's literally in the request body.

This is the function that sends the data, it takes it from the value attribute inside a button.

function sendThefknData(mangaId) {
        axios.post('/saveManga', {
            mangaId: mangaId
        })
            .then(response => {
                console.log('Manga saved successfully:', response.data);
            })
            .catch(error => {
                console.error('There was an error saving the manga:', error);
            });
    }

this is here is the controller endpoint

@PostMapping("/saveManga")
    public ResponseEntity<String> saveManga(@RequestParam("mangaId") String mangaId, HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User not logged in.");
            }

            System.out.println("Manga ID: " + mangaId);
            System.out.println("User ID from session: " + userId);

            usermangainfo.insertUserMangas(userId, mangaId);

            return ResponseEntity.ok("Manga saved successfully.");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error saving manga: " + e.getMessage());
        }
    }

I honestly have no idea what the issue would be, I tried googling and tried my luck with chatgpt but to no avail.Network


Solution

  • Hey you are sending request param in wrong way. Use the below

    axios.post(/saveManga?mangaId=${mangaId})

    this should work.