3
votes

I'm getting my token from an API but unfortunately my API is returning 400 bad request. I've already checked my api via Postman and it's working fine there. Kindly let me know solution or any mistake.

async componentWillMount(){
 axios.post('http://api.myapiurl.com/token', {
                grant_type: 'PASSWORD',
                username: 'MY_USERNAME',
                password: 'MY_PASSWORD'
            }, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(response => {
                console.log(response.data)
            }).catch(err => console.log("api Erorr: ", err.message))
}

error in catch

Request failed with status code 400

1
@iRohitBhatia Please checkZaIn KhAn
Do you send the same headers in the postman like? Maybe you just need to send like this: ` headers: {'Content-Type': 'application/json'}`SuleymanSah
I'm sending the same headersZaIn KhAn
Can you try to send the header in my comment?SuleymanSah
Content-Type:application/x-www-form-urlencodedZaIn KhAn

1 Answers

2
votes

Solve by myself using QueryString.stringify(). I just pass the body into QueryString.stringify() like below:

axios.post('http://api.apiurl.com/token', QueryString.stringify({
            grant_type: 'MY_GRANT_TYPE',
            username: 'MY_USERNAME',
            password: 'MY_PASSWORD'
        }), {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            }
        }).then(response => {
            console.log(response.data)
        }).catch(err => console.log("api Erorr: ", err.response))