天天看點

Axios 入門學習 安裝 簡單使用 執行個體使用 詳細配置 攔截器 處理錯誤 取消

作者:CShap新勢力

安裝

$ npm install axios           

cdn 國内

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>           
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> 國外           

簡單案例 Get

//擷取使用者
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
});           

上面代碼另一種寫法

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
});             

use async/await

async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

let user = getUser();           

執行POST請求

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

執行多個并發請求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
});           

通過将相關配置來送出請求axios

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

請求方法别名

所有常見的請求方法提供了别名

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

别名樣例

axios.request({
   method:'GET',
   url: 'http://localhost:3000/comments'
}).then(response => {
   console.log(response);
})           
axios.post(
   'http://localhost:3000/comments', 
   {
     "body": "喜大普奔",
     "postId": 2
   }).then(response => {
   console.log(response);
})           

請求配置

這些是用于送出請求的可用配置選項。僅url是必需的。GET如果method未指定,請求将預設為。

{
  // `url`是将用于請求的伺服器URL
  url: '/user',

  // `method`是送出請求時使用的請求方法
  method: 'get', //  預設

  // `baseURL`将被添加到`url`前面,除非`url`是絕對的。
  // 可以友善地為 axios 的執行個體設定`baseURL`,以便将相對 URL 傳遞給該執行個體的方法。
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest`允許在請求資料發送到伺服器之前對其進行更改
  // 這隻适用于請求方法'PUT','POST'和'PATCH'
  // 數組中的最後一個函數必須傳回一個字元串,一個 ArrayBuffer或一個 Stream
  transformRequest: [function (data, headers) {
    //做任何你想要的資料轉換

    return data;
  }],

  //`transformResponse`允許在 then / catch之前對響應資料進行更改
  transformResponse: [function (data) {
    // 執行任何要轉換資料的操作

    return data;
  }],

  // `headers`是要發送的自定義 headers
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params`是要與請求一起發送的URL參數
  // 必須是純對象或URLSearchParams對象
  params: {
    ID: 12345
  },

  // `paramsSerializer`是一個可選的函數,負責序列化`params`
  paramsSerializer: {
    indexes: null // array indexes format (null - no brackets, false - empty brackets, true - brackets with indexes)
  },

  // `data`是要作為請求主體發送的資料
  // 僅适用于請求方法“PUT”,“POST”和“PATCH”
  //當沒有設定`transformRequest`時,必須是以下類型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
  
  // 将資料發送到正文的文法替代方案
  // method post
  //隻發送value,不發送key
  data: 'Country=Brasil&City=Belo Horizonte',

  //  `timeout`指定請求逾時之前的毫秒數。
  // 如果請求的時間超過'timeout',請求将被中止。
  timeout: 1000, // default is `0` (no timeout)

  // `withCredentials`訓示是否跨站點通路控制請求 ,是否帶上Cookie
  // should be made using credentials
  withCredentials: false, // default

  // `adapter'允許自定義處理請求,這使得測試更容易。
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth'表示應該使用 HTTP 基本認證,并提供憑據。
  // 這将設定一個`Authorization'頭,覆寫任何現有的`Authorization'自定義頭,使用`headers`設定。
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // “responseType”表示伺服器将響應的資料類型
  // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `responseEncoding` 表示伺服器将響應的資料編碼 (Node.js only)
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

  // `xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名稱
  xsrfCookieName: 'XSRF-TOKEN', // default

  //  `xsrfHeaderName`是攜帶xsrf令牌值的http頭的名稱
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress`允許處理上傳的進度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress`允許處理下載下傳的進度事件
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength`定義允許的http響應内容的最大大小
  maxContentLength: 2000,

  // `maxBodyLength` (Node only option) 定義允許的http請求内容的最大大小(以位元組為機關)
  maxBodyLength: 2000,

  // `validateStatus` 定義是否解析或拒絕給定的promise
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects`定義在node.js中要遵循的重定向的最大數量。
  // 如果設定為0,則不會遵循重定向。
  maxRedirects: 21, // default

  // `beforeRedirect` defines a function that will be called before redirect.
  // Use this to adjust the request options upon redirecting,
  // to inspect the latest response headers,
  // or to cancel the request by throwing an error
  // If maxRedirects is set to 0, `beforeRedirect` is not used.
  beforeRedirect: (options, { headers }) => {
    if (options.hostname === "example.com") {
      options.auth = "user:password";
    }
  },

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // `proxy` defines the hostname, port, and protocol of the proxy server.
  // You can also define your proxy using the conventional `http_proxy` and
  // `https_proxy` environment variables. If you are using environment variables
  // for your proxy configuration, you can also define a `no_proxy` environment
  // variable as a comma-separated list of domains that should not be proxied.
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  // If the proxy server uses HTTPS, then you must set the protocol to `https`. 
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // cancelToken”指定可用于取消請求的取消令牌
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  }),

  // an alternative way to cancel Axios requests using AbortController
  signal: new AbortController().signal,

  // `decompress` indicates whether or not the response body should be decompressed 
  // automatically. If set to `true` will also remove the 'content-encoding' header 
  // from the responses objects of all decompressed responses
  // - Node only (XHR cannot turn off decompression)
  decompress: true // default

  // `insecureHTTPParser` boolean.
  // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
  // This may allow interoperability with non-conformant HTTP implementations.
  // Using the insecure parser should be avoided.
  // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
  // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
  insecureHTTPParser: undefined // default

  // transitional options for backward compatibility that may be removed in the newer versions
  transitional: {
    // silent JSON parsing mode
    // `true`  - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
    // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
    silentJSONParsing: true, // default value for the current Axios version

    // try to parse the response string as JSON even if `responseType` is not 'json'
    forcedJSONParsing: true,
    
    // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
    clarifyTimeoutError: false,
  },

  env: {
    // The FormData class to be used to automatically serialize the payload into a FormData object
    FormData: window?.FormData || global?.FormData
  },

  formSerializer: {
      visitor: (value, key, path, helpers)=> {}; // custom visitor funaction to serrialize form values
      dots: boolean; // use dots instead of brackets format
      metaTokens: boolean; // keep special endings like {} in parameter key 
      indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
  }
}           

響應模式

請求的響應包含以下資訊。

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the HTTP headers that the server responded with
  // All header names are lowercase and can be accessed using the bracket notation.
  // Example: `response.headers['content-type']`
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}           

使用時then,您将收到如下響應:

axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
});           

配置預設值

您可以指定将應用于每個請求的配置預設值。

全局 axios 預設值

axios.defaults.baseURL = 'https://api.example.com';

// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
// See below for an example using Custom instance defaults instead.
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 
axios.defaults.headers.common['Authorization'] = "Bearer " + access_token; //Jwt
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';           

自定義執行個體預設值

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;           

配置優先順序

axios.defaults.config < instance.config < request.config

// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});           

攔截器

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

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

可以将攔截器添加到 axios 的自定義執行個體中。

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});           

還可以清除請求或響應的所有攔截器。

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
instance.interceptors.request.clear(); // Removes interceptors from requests
instance.interceptors.response.use(function () {/*...*/});
instance.interceptors.response.clear(); // Removes interceptors from responses           

請求攔截器時,預設情況下被認為是異步執行的。當主線程被阻塞時,這可能會導緻 axios 請求的執行延遲。如果您的請求攔截器是同步的,您可以向選項對象添加一個标志,該标志将告訴 axios 同步運作代碼并避免請求執行中的任何延遲。

axios.interceptors.request.use(function (config) {
  config.headers.test = 'I am only a header!';
  return config;
}, null, { synchronous: true });           

如果要根據運作時檢查執行特定攔截器,可以runWhen向選項對象添加一個函數。當且僅當傳回的runWhen是時,攔截器不會被執行false。該函數将使用配置對象調用(不要忘記您也可以将自己的參數綁定到它)。當您有一個隻需要在特定時間運作的異步請求攔截器時,這會很友善。

function onGetCall(config) {
  return config.method === 'get';
}
axios.interceptors.request.use(function (config) {
  config.headers.test = 'special get headers';
  return config;
}, null, { runWhen: onGetCall });           

處理錯誤

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 請求已發出,伺服器以狀态代碼響應
      //超出2xx的範圍
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // 已送出請求,但未收到響應
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // 設定請求時發生了觸發錯誤的問題
      console.log('Error', error.message);
    }
    console.log(error.config);
  });           

使用validateStatusconfig 選項,您可以定義應引發錯誤的 HTTP 代碼。

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // 僅當狀态代碼小于500時解決
  }
})           

使用toJSON您可以獲得一個包含有關 HTTP 錯誤的更多資訊的對象。

axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
});           

取消

通過将執行器函數傳遞給構造函數來建立取消标記CancelToken:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();           

有個很好的場景,如果在搶購的時候,使用者瘋狂的搶購按鈕,但是伺服器每次響應至少需要2-3秒。那麼就會瘋狂的發請求,加重伺服器的負擔。這個時候取消就很有用了。使用者可以瘋狂的點,但我們可以取消啊。看代碼案例

//擷取按鈕
const btns = document.querySelectorAll('button');

//2.聲明全局變量
let cancel = null;

//發送請求
btns[0].onclick = function(){
  //檢測上一次的請求是否已經完成
  if(cancel !== null){
    //取消上一次的請求
    cancel();
  }
  
  axios({
    method: 'GET',
    url: 'http://localhost:3000/posts',
    //1. 添加配置對象的屬性
    cancelToken: new axios.CancelToken(function(c){
      //3. 将 c 的值指派給 cancel
      cancel = c;
    })
  }).then(response => {
    console.log(response);
    //将 cancel 的值初始化
    cancel = null;
  })  
}           
Axios 入門學習 安裝 簡單使用 執行個體使用 詳細配置 攔截器 處理錯誤 取消

使用application/x-www-form-urlencoded格式

URL搜尋參數

預設情況下,axios 将 JavaScript 對象序列化為JSON. application/x-www-form-urlencoded要以該格式發送資料,您可以使用絕大多數浏覽器都支援的URLSearchParamsAPI

const params = new URLSearchParams({ foo: 'bar' });
params.append('extraparam', 'value');
axios.post('/foo', params);           

查詢字元串

或者以另一種方式(ES6),

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);           

自動序列化為 URLSearchParams

如果 content-type-header 設定為“application/x-www-form-urlencoded”,Axios 會自動将資料對象序列化為 urlencoded 格式。

const data = {
  x: 1,
  arr: [1, 2, 3],
  arr2: [1, [2], 3],
  users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
};

await axios.postForm('https://postman-echo.com/post', data,
  {headers: {'content-type': 'application/x-www-form-urlencoded'}}
);           

伺服器将把它處理為

{
    x: '1',
    'arr[]': [ '1', '2', '3' ],
    'arr2[0]': '1',
    'arr2[1][0]': '2',
    'arr2[2]': '3',
    'users[0][name]': 'Peter',
    'users[0][surname]': 'griffin',
    'users[1][name]': 'Thomas',
    'users[1][surname]': 'Anderson'
  }           

使用multipart/form-data格式

表單資料

要将資料發送,multipart/formdata您需要傳遞一個 formData 執行個體作為有效負載。Content-Type不需要設定标頭,因為 Axios 根據有效負載類型猜測它。

const formData = new FormData();
formData.append('foo', 'bar');
axios.post('https://httpbin.org/post', formData);           

自動序列化為 FormData

從 開始v0.27.0,如果請求Content-Type 标頭設定為,Axios 支援自動對象序列化為 FormData 對象multipart/form-data。

以下請求将以 FormData 格式送出資料

import axios from 'axios';

axios.post('https://httpbin.org/post', {x: 1}, {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
}).then(({data})=> console.log(data));           

假設我們有一個像這樣的對象:

const obj = {
  x: 1,
  arr: [1, 2, 3],
  arr2: [1, [2], 3],
  users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
  'obj2{}': [{x:1}]
};           

以下步驟将由 Axios 序列化器内部執行:

const formData= new FormData();
formData.append('x', '1');
formData.append('arr[]', '1');
formData.append('arr[]', '2');
formData.append('arr[]', '3');
formData.append('arr2[0]', '1');
formData.append('arr2[1][0]', '2');
formData.append('arr2[2]', '3');
formData.append('users[0][name]', 'Peter');
formData.append('users[0][surname]', 'Griffin');
formData.append('users[1][name]', 'Thomas');
formData.append('users[1][surname]', 'Anderson');
formData.append('obj2{}', '[{"x":1}]');           

axios 支援以下快捷方法:postForm、putForm,patchForm 這隻是對應的 http 方法,頭Content-Type預設為multipart/form-data。

上傳檔案

單個檔案

await axios.postForm('https://httpbin.org/post', {
  'myVar' : 'foo',
  'file': document.querySelector('#fileInput').files[0] 
});           

多個檔案作為multipart/form-data.

await axios.postForm('https://httpbin.org/post', {
  'files[]': document.querySelector('#fileInput').files 
});           

FileList可以直接傳遞對象

await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)           

所有檔案都将使用相同的字段名稱發送:files[]

HTML 表單送出

将 HTML Form 元素作為有效負載傳遞,以将其作為multipart/form-data内容送出。

await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));           

FormData并且對象也可以通過将headers 顯式設定為來HTMLForm送出:JSON Content-Type application/json

await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
  headers: {
    'Content-Type': 'application/json' //告訴服務端是json方式送出的
  }
})           

例如,表格

<form id="form">
  <input type="text" name="foo" value="1">
  <input type="text" name="deep.prop" value="2">
  <input type="text" name="deep prop spaced" value="3">
  <input type="text" name="baz" value="4">
  <input type="text" name="baz" value="5">

  <select name="user.age">
    <option value="value1">Value 1</option>
    <option value="value2" selected>Value 2</option>
    <option value="value3">Value 3</option>
  </select>

  <input type="submit" value="Save">
</form>           

将作為以下 JSON 對象送出:

{
  "foo": "1",
  "deep": {
    "prop": {
      "spaced": "3"
    }
  },
  "baz": [
    "4",
    "5"
  ],
  "user": {
    "age": "value2"
  }
}           

繼續閱讀