最小範例

使用 axios 的小範例

注意:CommonJS 用法

為了在使用 CommonJS 匯入時取得 TypeScript 型別(用於 IntelliSense/自動完成)require(),請使用以下方法

const axios = require('axios').default;

// axios.<method> will now provide autocomplete and parameter typings

範例

執行 GET 要求

const axios = require('axios');

// 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);
  })
  .finally(function () {
    // always executed
  });

// 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);
  })
  .finally(function () {
    // always executed
  });  

// 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);
  }
}

注意:async/await 是 ECMAScript 2017 的一部分,且不支援 Internet Explorer 和較舊的瀏覽器,因此請小心使用。