Search code examples
javascriptposthttp-status-code-422

Getting a 422 Error on Post request, but I think my request is being sent correclty


I have to make a POST request, to an API that was given to me.

I am supposed to send some data to it and get back an JWT token.

The data i have to send is an object called data like this:

{
    "firstName": "Jane",
    "address": "Lohmühlenstraße 65",
    "numberOfChildren": 2,
    "occupation": "EMPLOYED",
    "email": "[email protected]"
}

And the API docu looks like this:

curl https://challenge-dot-popsure-204813.appspot.com/user \
-H 'Content-Type: application/json' \
-d '{"firstName":"Jane","address":"Lohmühlenstraße 65","numberOfChildren":2,"occupation":"EMPLOYED","email":"[email protected]"}' \
-X POST

I am sending with axios a POST request, with an object, but i get an 422 Error:

Failed to load resource: the server responded with a status of 422 ()

This is my POST request, where data is the object above:

    axios.post('https://challenge-dot-popsure-204813.appspot.com/user', data)
    .then(function (response) {
      debugger
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

Any ideas what can be the issue?


Solution

  • I was able to reproduce the 422 error by removing or invalidating the JSON data. For instance remove/rename the "firstName" property.

    Example:

    {
        "name": "Jane",
        "address": "Lohmühlenstraße 65",
        "numberOfChildren": 2,
        "occupation": "EMPLOYED",
        "email": "[email protected]"
    }
    

    Resulted In: 422 Unprocessable Entity

    {
        "errors": {
            "firstName": [
                "Missing data for required field."
            ],
            "name": [
                "Unknown field."
            ]
        }
    }
    

    Plunker

    I think the issue you are facing is that the data you are expecting is not all there when you make the axios.post resulting in the error you are seeing. Make sure that the data sent in the request contains all valid fields and values beforehand.