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 response below

Request failed with status code 400 - node_modules\axios\lib\core\createError.js:16:24 in createError - node_modules\axios\lib\core\settle.js:18:6 in settle - ... 10 more stack frames from framework internals

Postman Screenshot

4
You need to check on logs on server to see why 400 and fix that. With just the frontend code, we will not be able to tell what the server requires.Panther
@Zaln KhAn you must be getting something in response error. check that because what error are you facing we can't find with this code.akhtarvahid
The axios document says to send the params for www-form-urlencoded in a different way. Are you following that ?? github.com/axios/…Panther
updated please check.ZaIn KhAn
By default, the params you send will be parsed to json. To send it in www-form-urlencoded, you need to follow the documentation.Panther

4 Answers

1
votes

From what I can see you are sending json data, but your Content-Type header is set to application/x-www-form-urlencoded; charset=UTF-8. if your api is expecting json then it should be application/json.

1
votes

try using fetch instead, might be some axios bug, you dont need to add any libraries, here is an example:

fetch("http://api.myapiurl.com/token", {
  method: "POST", // *GET, POST, PUT, DELETE, etc.
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    grant_type: "PASSWORD",
    username: "MY_USERNAME",
    password: "MY_PASSWORD"
  }) 
})
  .then(res => {
    res.json();
  })
  .then(data => console.log(data))  // ur data is here
  .catch(err => console.log("api Erorr: ", err));
1
votes

It is Solved by 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))
0
votes

First install the package axios from the url https://www.npmjs.com/package/react-native-axios Then create two service for handling get and post request so that you can reuse them

GetService.js

import axios from 'axios'; 
let constant = {
    baseurl:'https://www.sampleurl.com/'
};
let config = {

    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

export const GetService = (data,Path,jwtKey) => {
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
    }

    try{
        return axios.get(
                            constant.baseUrl+'api/'+Path, 
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}    

PostService.js

import axios from 'axios'; 
let constant = {
    baseurl:'https://www.sampleurl.com/'
};
let config = {

    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

export const PostService = (data,Path,jwtKey) => {
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
    }

    try{
        return axios.post(
                            constant.baseUrl+'api/'+Path, 
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}

Sample code for using get and post services is given below

import { PostService } from './PostService';
import { GetService } from './GetService';


let uploadData = new FormData();
uploadData.append('key1', this.state.value1);
uploadData.append('key2', this.state.value2);
//uploadData.append('uploads', { type: data.mime, uri: data.path, name: "samples" });

let jwtKey = ''; // Authentication key can be added here
PostService(uploadData, 'postUser.php', jwtKey).then((resp) => {
this.setState({ uploading: false });
    // resp.data will contain json data from server
}).catch(err => {
    // handle error here
});



GetService({}, 'getUser.php?uid='+uid, jwtKey).then((resp) => {
    // resp.data will contain json data from server
}).catch(err => {
    // handle error here
});

Reference from one of my another post Post action API with object parameter within the URL If you have any doubts, feel free to know