axios---get和post用法詳解


參考網址:https://www.npmjs.com/package/axios

1.axios發送get請求

const axios = require('axios');

1.1.參數寫在路徑后面

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

1.2.參數不寫在路徑后面

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345 } })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

1.3.用異步async/await語法

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

2.axios發送post請求

2.1.常規用法

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone' })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

2.2.復合用法

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

3.axios.all用法(Promise.all)

可以同時請求多個接口

axios.all( [getUserAccount(), getUserPermissions()])
    .then(  axios.spread(function(acct,perms))  )

4.axios攔截器

4.1.請求攔截---request

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

4.2.響應攔截---response

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM