1
votes

I've got a problem with sending POST request to a backend server (managed by Swagger UI). Below is the code snippet of POST function:

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const employee: IEmployee = {
          age: newEmployeeData.age,
          id: newEmployeeData.id,
          name: newEmployeeData.name,
          position: newEmployeeData.position,
        };

        axios
          .post("http://34.140.193.23/api/employees", JSON.stringify(employee), {
            headers: {
              "Content-Type": "application/json",
            },
          })
         .then((res) => setEmployeesData([...employeesData, res.data]))
         .catch((error) => {
           console.log("Error:", error);
         });
    };

When I call handleSubmit function, it throws me an error to the console like this:

Failed to load resource: the server responded with a status of 400 ()
createError.js:16 Uncaught (in promise) Error: Request failed with status code 400
at createError (createError.js:16:1)
at settle (settle.js:17:1)
at XMLHttpRequest.onloadend (xhr.js:66:1)

When I try to debug in Sources panel in Chrome DevTools it doesn't even return value for res variable. To be precise, it doesn't run .then statement at all.

Backend server: http://34.140.193.23/swagger-ui/#/employee-controller

Am I missing something? Thank you a lot for your help.

Wrong content type? Try application/text without JSON processing, if it reaches the then callback.gru
You don't need to stringify the data with axios. Are you sure your employee data is correct? Are age and id numbers instead of strings?anttud