在与axios的react-native中使用POST方法获取API数据 [英] Get API data with POST method in react-native with axios
问题描述
我需要使用axios在react-native应用程序中获取数据.我可以使用以下简单的GET方法获取数据:
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>
);
}
}
如何使用POST
方法从API获取数据,我还需要传递标头和api-用户名,api-password,apitoken?
How can i get data from API with POST
method and I also need to pass header and api-username,api-password, apitoken ?
我需要类似 https://stackoverflow.com/a/41358543/949003 的东西,但是要使用 AXIOS .
I need something like https://stackoverflow.com/a/41358543/949003 but with AXIOS.
我需要从 LINNWORK API中获取数据.如果有人这样做,请指导.他们首先需要授权,然后我才能从那里获取数据.因此,请先进行身份验证,然后再进行下一步.
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.
推荐答案
axios post
方法采用3个参数,即url,data和配置.
axios post
method takes 3 arguments i.e. url, data & config.
您可以按以下方式构建axios发布请求:
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
}
}
);
根据您的情况,您需要访问https://api.linnworks.net/api/Inventory/GetCategories
,根据文档需要Authorization
标头中的auth api中的token
.因此,您通过axios的GET请求将是:
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);
})
这篇关于在与axios的react-native中使用POST方法获取API数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!