1const axios = require('axios');
2
3// Make a request for a user with a given ID
4axios.get('/user?ID=12345')
5 .then(function (response) {
6 // handle success
7 console.log(response);
8 })
9 .catch(function (error) {
10 // handle error
11 console.log(error);
12 })
13 .then(function () {
14 // always executed
15 });
16
17// Optionally the request above could also be done as
18axios.get('/user', {
19 params: {
20 ID: 12345
21 }
22 })
23 .then(function (response) {
24 console.log(response);
25 })
26 .catch(function (error) {
27 console.log(error);
28 })
29 .then(function () {
30 // always executed
31 });
32
33// Want to use async/await? Add the `async` keyword to your outer function/method.
34async function getUser() {
35 try {
36 const response = await axios.get('/user?ID=12345');
37 console.log(response);
38 } catch (error) {
39 console.error(error);
40 }
41}
1import qs from 'qs';
2const data = { 'bar': 123 };
3const options = {
4 method: 'POST',
5 headers: { 'content-type': 'application/x-www-form-urlencoded' },
6 data: qs.stringify(data),
7 url,
8};
9axios(options);
1// GET request for remote image
2axios({
3 method: 'get',
4 url: 'http://bit.ly/2mTM3nY',
5 responseType: 'stream'
6})
7 .then(function(response) {
8 response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
9});
1// Make a request for a user with a given ID
2axios.get('/user?ID=12345')
3 .then(function (response) {
4 console.log(response);
5 })
6 .catch(function (error) {
7 console.log(error);
8 });
9
10// Optionally the request above could also be done as
11axios.get('/user', {
12 params: {
13 ID: 12345
14 }
15 })
16 .then(function (response) {
17 console.log(response);
18 })
19 .catch(function (error) {
20 console.log(error);
21 });
1// lets you create custom pre-configured fetch api call!
2const getUser = axios.create({
3 baseURL: 'https://randomuser.me/api/', // we define url
4 timeout: 1000, // (optional) set timeout
5 headers: {'X-Custom-Header': 'foobar'} // pass headers
6});
7
8// use later like this
9getUser().then(response => console.log(response))