nodejs請求庫axios(一)


一.介紹

  Axios 是一個基於 promise 網絡請求庫,作用於node.js 和瀏覽器中。 它是 isomorphic 的(即同一套代碼可以運行在瀏覽器和node.js中)。在服務端它使用原生 node.js http 模塊, 而在客戶端 (瀏覽端) 則使用 XMLHttpRequests。

二.特性

  • 從瀏覽器創建 XMLHttpRequests
  • 從 node.js 創建 http 請求
  • 支持 Promise API
  • 攔截請求和響應
  • 轉換請求和響應數據
  • 取消請求
  • 自動轉換JSON數據
  • 客戶端支持防御XSRF

三.安裝

使用 npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 yarn:

$ yarn add axios

使用 jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

使用 unpkg CDN:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

 

四.基本使用

  使用axios的基本用例

  為了在CommonJS中使用 require() 導入時獲得TypeScript類型推斷(智能感知/自動完成),請使用以下方法:

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

// axios.<method> 能夠提供自動完成和參數類型推斷功能

  1.發起一個 GET 請求

axios.get('http://httpbin.org/get?a=b&c=d')
    .then(function (response) {
        // 處理成功情況
        console.log(response.data);
        //response有幾個重要的屬性
        response.data
        response.status
        response.headers
    })
    .catch(function (error) {
        // 處理錯誤情況
        console.log(error);
    })
    .then(function () {
        // 總是會執行
        console.log('總是會執行')
    });

  結果:

{
  args: { a: 'b', c: 'd' },
  headers: {
    Accept: 'application/json, text/plain, */*',
    Host: 'httpbin.org',
    'User-Agent': 'axios/0.26.1',
    'X-Amzn-Trace-Id': 'Root=1-62544a3c-4a61d96b1b07888b2d60a475'
  },
  origin: '183.8.148.251',
  url: 'http://httpbin.org/get?a=b&c=d'
}

  另一種寫法

axios.get('http://httpbin.org/get', {
    params: {
        ID: 12345
    }
})
    .then(function (response) {
        console.log(response.data);
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
        // 總是會執行
        console.log("總是會執行")
    });

  也支持異步寫法:

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

   2.發起一個 POST 請求

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

  3.發起多個並發請求

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 API

  可以向 axios 傳遞相關配置來創建請求

  1.axios(config)
// 發起一個post請求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

  下載圖片

// 在 node.js 用GET請求獲取遠程圖片
axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });

  2.axios(url[, config])

// 發起一個 GET 請求 (默認請求方式)
axios('/user/12345');

  

  請求方式別名

  為了方便起見,已經為所有支持的請求方法提供了別名。

  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]])
  注意:

    在使用別名方法時, urlmethoddata 這些屬性都不必在配置中指定

六.Axios 實例

  axios.create([config])

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

實例方法

以下是可用的實例方法。指定的配置將與實例的配置合並。

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#getUri([config])

七.請求配置

  這些是創建請求時可以用的配置選項。只有 url 是必需的。如果沒有指定 method,請求將默認使用 GET 方法。

{
  // `url` 是用於請求的服務器 URL
  url: '/user',

  // `method` 是創建請求時使用的方法
  method: 'get', // 默認值

  // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。
  // 它可以通過設置一個 `baseURL` 便於為 axios 實例的方法傳遞相對 URL
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` 允許在向服務器發送前,修改請求數據
  // 它只能用於 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
  // 數組中最后一個函數必須返回一個字符串, 一個Buffer實例,ArrayBuffer,FormData,或 Stream
  // 你可以修改請求頭。
  transformRequest: [function (data, headers) {
    // 對發送的 data 進行任意轉換處理

    return data;
  }],

  // `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據
  transformResponse: [function (data) {
    // 對接收的 data 進行任意轉換處理

    return data;
  }],

  // 自定義請求頭
  headers: {'X-Requested-With': 'XMLHttpRequest'},

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

  // `paramsSerializer`是可選方法,主要用於序列化`params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` 是作為請求體被發送的數據
  // 僅適用 'PUT', 'POST', 'DELETE 和 'PATCH' 請求方法
  // 在沒有設置 `transformRequest` 時,則必須是以下類型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 瀏覽器專屬: FormData, File, Blob
  // - Node 專屬: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
  
  // 發送請求體數據的可選語法
  // 請求方式 post
  // 只有 value 會被發送,key 則不會
  data: 'Country=Brasil&City=Belo Horizonte',

  // `timeout` 指定請求超時的毫秒數。
  // 如果請求時間超過 `timeout` 的值,則請求會被中斷
  timeout: 1000, // 默認值是 `0` (永不超時)

  // `withCredentials` 表示跨域請求時是否需要使用憑證
  withCredentials: false, // default

  // `adapter` 允許自定義處理請求,這使測試更加容易。
  // 返回一個 promise 並提供一個有效的響應 (參見 lib/adapters/README.md)。
  adapter: function (config) {
    /* ... */
  },

  // `auth` HTTP Basic Auth
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` 表示瀏覽器將要響應的數據類型
  // 選項包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
  // 瀏覽器專屬:'blob'
  responseType: 'json', // 默認值

  // `responseEncoding` 表示用於解碼響應的編碼 (Node.js 專屬)
  // 注意:忽略 `responseType` 的值為 'stream',或者是客戶端請求
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // 默認值

  // `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名稱
  xsrfCookieName: 'XSRF-TOKEN', // 默認值

  // `xsrfHeaderName` 是帶有 xsrf token 值的http 請求頭名稱
  xsrfHeaderName: 'X-XSRF-TOKEN', // 默認值

  // `onUploadProgress` 允許為上傳處理進度事件
  // 瀏覽器專屬
  onUploadProgress: function (progressEvent) {
    // 處理原生進度事件
  },

  // `onDownloadProgress` 允許為下載處理進度事件
  // 瀏覽器專屬
  onDownloadProgress: function (progressEvent) {
    // 處理原生進度事件
  },

  // `maxContentLength` 定義了node.js中允許的HTTP響應內容的最大字節數
  maxContentLength: 2000,

  // `maxBodyLength`(僅Node)定義允許的http請求內容的最大字節數
  maxBodyLength: 2000,

  // `validateStatus` 定義了對於給定的 HTTP狀態碼是 resolve 還是 reject promise。
  // 如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),
  // 則promise 將會 resolved,否則是 rejected。
  validateStatus: function (status) {
    return status >= 200 && status < 300; // 默認值
  },

  // `maxRedirects` 定義了在node.js中要遵循的最大重定向數。
  // 如果設置為0,則不會進行重定向
  maxRedirects: 5, // 默認值

  // `socketPath` 定義了在node.js中使用的UNIX套接字。
  // e.g. '/var/run/docker.sock' 發送請求到 docker 守護進程。
  // 只能指定 `socketPath` 或 `proxy` 。
  // 若都指定,這使用 `socketPath` 。
  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` 定義了代理服務器的主機名,端口和協議。
  // 您可以使用常規的`http_proxy` 和 `https_proxy` 環境變量。
  // 使用 `false` 可以禁用代理功能,同時環境變量也會被忽略。
  // `auth`表示應使用HTTP Basic auth連接到代理,並且提供憑據。
  // 這將設置一個 `Proxy-Authorization` 請求頭,它會覆蓋 `headers` 中已存在的自定義 `Proxy-Authorization` 請求頭。
  // 如果代理服務器使用 HTTPS,則必須設置 protocol 為`https`
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // see https://axios-http.com/zh/docs/cancellation
  cancelToken: new CancelToken(function (cancel) {
  }),

  // `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 // 默認值

}

 八.響應結構

  一個請求的響應包含以下信息。

{
  // `data` 由服務器提供的響應
  data: {},

  // `status` 來自服務器響應的 HTTP 狀態碼
  status: 200,

  // `statusText` 來自服務器響應的 HTTP 狀態信息
  statusText: 'OK',

  // `headers` 是服務器響應頭
  // 所有的 header 名稱都是小寫,而且可以使用方括號語法訪問
  // 例如: `response.headers['content-type']`
  headers: {},

  // `config` 是 `axios` 請求的配置信息
  config: {},

  // `request` 是生成此響應的請求
  // 在node.js中它是最后一個ClientRequest實例 (in redirects),
  // 在瀏覽器中則是 XMLHttpRequest 實例
  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);
  });

  當使用 catch,或者傳遞一個rejection callback作為 then 的第二個參數時,響應可以通過 error 對象被使用,正如在錯誤處理部分解釋的那樣。

九.默認配置

  您可以指定默認配置,它將作用於每個請求。

  全局 axios 默認值

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

  自定義實例默認值

// 創建實例時配置默認值
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 創建實例后修改默認值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

  配置的優先級

  配置將會按優先級進行合並。它的順序是:在lib/defaults.js中找到的庫默認值,然后是實例的 defaults 屬性,最后是請求的 config 參數。后面的優先級要高於前面的。下面有一個例子。

// 使用庫提供的默認配置創建實例
// 此時超時配置的默認值是 `0`
const instance = axios.create();

// 重寫庫的超時默認值
// 現在,所有使用此實例的請求都將等待2.5秒,然后才會超時
instance.defaults.timeout = 2500;

// 重寫此請求的超時時間,因為該請求需要很長時間
instance.get('/longRequest', {
  timeout: 5000
});

十.攔截器

  在請求或響應被 then 或 catch 處理前攔截它們。

// 添加請求攔截器
axios.interceptors.request.use(function (config) {
    // 在發送請求之前做些什么
    return config;
  }, function (error) {
    // 對請求錯誤做些什么
    return Promise.reject(error);
  });

// 添加響應攔截器
axios.interceptors.response.use(function (response) {
    // 2xx 范圍內的狀態碼都會觸發該函數。
    // 對響應數據做點什么
    return response;
  }, function (error) {
    // 超出 2xx 范圍的狀態碼都會觸發該函數。
    // 對響應錯誤做點什么
    return Promise.reject(error);
  });

  如果你稍后需要移除攔截器,可以這樣:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

  可以給自定義的 axios 實例添加攔截器。

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

十一.錯誤處理

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` 在瀏覽器中是 XMLHttpRequest 的實例,
      // 而在node.js中是 http.ClientRequest 的實例
      console.log(error.request);
    } else {
      // 發送請求時出了點問題
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

  使用 validateStatus 配置選項,可以自定義拋出錯誤的 HTTP code。

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // 處理狀態碼小於500的情況
  }
})

  使用 toJSON 可以獲取更多關於HTTP錯誤的信息。

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

 

十二.取消請求

 AbortController

  從 v0.22.0 開始,Axios 支持以 fetch API 方式—— AbortController 取消請求:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// 取消請求
controller.abort()

  

  CancelToken deprecated

  您還可以使用 cancel token 取消一個請求。

  Axios 的 cancel token API 是基於被撤銷 cancelable promises proposal

  此 API 從 v0.22.0 開始已被棄用,不應在新項目中使用。

可以使用 CancelToken.source 工廠方法創建一個 cancel token ,如下所示:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // 處理錯誤
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// 取消請求(message 參數是可選的)
source.cancel('Operation canceled by the user.');

  也可以通過傳遞一個 executor 函數到 CancelToken 的構造函數來創建一個 cancel token:

onst CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函數接收一個 cancel 函數作為參數
    cancel = c;
  })
});

// 取消請求
cancel();

  

注意: 可以使用同一個 cancel token 或 signal 取消多個請求。

在過渡期間,您可以使用這兩種取消 API,即使是針對同一個請求:

const controller = new AbortController();

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token,
  signal: controller.signal
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // 處理錯誤
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// 取消請求 (message 參數是可選的)
source.cancel('Operation canceled by the user.');
//
controller.abort(); // 不支持 message 參數

 

十三.請求體編碼

  默認情況下,axios將 JavaScript 對象序列化為 JSON 。 要以application/x-www-form-urlencoded格式發送數據,您可以使用以下選項之一。

  瀏覽器

  在瀏覽器中,可以使用URLSearchParams API,如下所示:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

請注意,不是所有的瀏覽器(參見 caniuse.com)都支持 URLSearchParams ,但是可以使用polyfill (確保 polyfill 全局環境)

或者, 您可以使用qs 庫編碼數據:

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

或者用另一種方式 (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);

Node.js

Query string

在 node.js 中, 可以使用 querystring 模塊,如下所示:

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

或者從'url module'中使用'URLSearchParams',如下所示:

const url = require('url');
const params = new url.URLSearchParams({ foo: 'bar' });
axios.post('http://something.com/', params.toString());

您也可以使用 qs 庫。

注意

如果需要對嵌套對象進行字符串化處理,則最好使用 qs 庫,因為 querystring 方法在該用例中存在已知問題(https://github.com/nodejs/node-v0.x-archive/issues/1665)。

Form data

在 node.js, 您可以使用 form-data 庫,如下所示:

const FormData = require('form-data');
 
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));

axios.post('https://example.com', form, { headers: form.getHeaders() })

或者, 使用一個攔截器:

axios.interceptors.request.use(config => {
  if (config.data instanceof FormData) {
    Object.assign(config.headers, config.data.getHeaders());
  }
  return config;
});

 


免責聲明!

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



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