REST API Post Error: The body of the request is not valid JSON

7.4k Views Asked by At

I am doing a post request from react client via axios. The post request is to microsoft custom translator api. For some reason , I keep getting 400 error.

When I checked the error response under chrome's network tab, I see this error => {"code":400074,"message":"The body of the request is not valid JSON."}

This post request works perfectly fine with postman. What am I missing here ?

let config = {
            headers: {
                'Content-Type': 'application/json',
                'Ocp-Apim-Subscription-Key': '<valid-key>',
                
            },
            params: {
                'api-version': '3.0',
                'to': 'de',
                'category': '<valid-category-id>'
            }
        }

        let data = {
            "body" : [
                {"Text": "Hello"}
            ]
        }

        axios.post('https://api.cognitive.microsofttranslator.com/translate/', data, config)
        .then((res) => console.log(res))
        .catch((err) => console.log(err));
2

There are 2 best solutions below

1
On

A post request does not usually have a trailing forward slash. Try removing the last forward slash so you url becomes:

'https://api.cognitive.microsofttranslator.com/translate'
0
On

It worked after I got rid of the "body" key.

let data =  [
                {"Text": "Hello"}
            ]