使用 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-username、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 post 请求:
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
,根据 docs 需要 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屋!