Search code examples
reactjsspring-bootpostman

Getting bad request from server (Spring boot) when using axios request


I'm currently stuck sending a request to my server and can not get a response. I have tried it on postman and it runs completely fine. However, when I try to put it on react, the back-end always response with a bad request.

Here is my code for the back-end

    @GetMapping(value = "/searchPatient")
    public ResponseEntity<?> searchPatients(@RequestParam String id_num,
                                            @RequestParam String name) {
        List<PatientForSearchDto> patientForSearchDtos =      patientService.viewSearchedPatient(id_num, name);
        return ResponseEntity.status(HttpStatus.OK).body(
                new ResponseObject("ok", "Success", patientForSearchDtos)
        );
    }

Here is my code for Front end (react)

    async function sendRequest () {
        const formData = new FormData();
        formData.append('id_num', id_num);
        formData.append('name', name);
        console.log(formData)
        console.log(formData.get('name'))
        console.log(formData.get('id_num'))
        const config = {
            method: 'get',
            url: 'http://localhost:8080/api/searchPatient',
            // headers : {
            //     'Content-Type': 'from-data'
            // },
            data : formData
        };

        await axios(config)
        .then(function (response) {
            console.log(JSON.stringify(response.data));
            setPatientList(response.data.data.object)
        })
        .catch(function (error) {
            console.log(error);
        });

    }

Here is what I get when sending request via postman

enter image description here

Here is when sending request using react

enter image description here


Solution

  • From the Axios docs about Request Config data param:

    // data is the data to be sent as the request body
    // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'

    So, data with GET method is not supported.
    Can't you use params instead?