Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get API data with POST method in react-native with axios

I need to get data in react-native app with axios. I can get data with simple GET method as below:

class AlbumList extends Component {

  state = { albums: [] };

componentWillMount() {
  //axios.get('https://rallycoding.herokuapp.com/api/music_albums') .then(response => console.log(response));
  axios.get('http://rallycoding.herokuapp.com/api/music_albums')

  .then(response => this.setState({ albums: response.data }));
        }
        renderAlbums() {
          return this.state.albums.map(album =>
          <AlbumDetail key={album.title} album={album} />);
         // return this.state.albums.map(album => <Text>{album.title}</Text>);
        }

render() {
    console.log(this.state);

return (
   <View>
        {this.renderAlbums()}
    </View>    
);
}
}

How can i get data from API with POST method and I also need to pass header and api-username,api-password, apitoken ?

I need something like https://stackoverflow.com/a/41358543/949003 but with AXIOS.

Edit:

I need to get data from LINNWORK API. if someone had done this please guide. They first need to authorize and then I can get data from there. So authrize and then next step.

like image 680
Jarnail S Avatar asked Jan 12 '18 10:01

Jarnail S


1 Answers

axios post method takes 3 arguments i.e. url, data & config.

you can structure axios post request as follows:

axios.post(
    'http://rallycoding.herokuapp.com/api/music_albums', 
    {
       'param1': 'value1',
       'param2': 'value2',
       //other data key value pairs
    },
    {
       headers: {
           'api-token': 'xyz',
            //other header fields
       }
    }
);

In your case you need to access https://api.linnworks.net/api/Inventory/GetCategories, which according to docs requires token from auth api in Authorization header. So your GET request via axios will be:

axios.get("https://api.linnworks.net/api/Inventory/GetCategories", { 
    headers: {
      'Authorization': 'token-from-auth-api'
    }
}).then((response) => {
    console.log(response.data);
})
like image 177
Deepansh Sachdeva Avatar answered Sep 29 '22 07:09

Deepansh Sachdeva