axios與ajax的區別及中文用戶指南

Ajax:javascript

Ajax 即「Asynchronous Javascript And XML」(異步 JavaScript 和 XML),是指一種建立交互式網頁應用的網頁開發技術。php

$.ajax({
   type: 'POST',
   url: url,
   data: data,
   dataType: dataType,
   success: function () {},
   error: function () {}
});

 

axios:html

用於瀏覽器和node.js的基於Promise的HTTP客戶端vue

1. 從瀏覽器製做XMLHttpRequestsjava

2. 讓HTTP從node.js的請求node

3. 支持Promise APIjquery

4. 攔截請求和響應ios

5. 轉換請求和響應數據git

6. 取消請求angularjs

7. 自動轉換爲JSON數據

8. 客戶端支持防止XSRF

它們來很大程度上分別受益於jquery和vuejs的廣發流行,可謂成也蕭何敗也蕭何,不過本質上都是要包裝XMLHttpRequest。只不過有時候單獨js請求服務器必不可少,額外引入jquery.ajax仍是有點怪,因此通常直接就使用axios。不過axios和vuejs並無什麼關係,甚至都沾不上親,純屬庫更加獨立、promise在寫法上更加流暢。

axios

基於promise用於瀏覽器和node.js的http客戶端

特色

  • 支持瀏覽器和node.js
  • 支持promise
  • 能攔截請求和響應
  • 能轉換請求和響應數據
  • 能取消請求
  • 自動轉換JSON數據
  • 瀏覽器端支持防止CSRF(跨站請求僞造)

安裝

npm安裝

$ npm install axios

bower安裝

$ bower install axios

經過cdn引入

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

例子

發起一個GET請求

// Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 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); }); 

發起一個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'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete })); 

axios api

能夠經過導入相關配置發起請求

axios(config)

// 發起一個POST請求 axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); 
// 獲取遠程圖片 axios({ method:'get', url:'http://bit.ly/2mTM3nY', responseType:'stream' }) .then(function(response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); 

axios(url[, config])

// 發起一個GET請求(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等屬性不用在config重複聲明。

同時發生的請求

一下兩個用來處理同時發生多個請求的輔助函數

axios.all(iterable)
axios.spread(callback)

建立一個實例

你能夠建立一個擁有通用配置的axios實例

axios.creat([config])

var 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]])

請求配置

下面是全部可用的請求配置項,只有url是必填,默認的請求方法是GET,若是沒有指定請求方法的話。

{
  // `url` 是請求的接口地址 url: '/user', // `method` 是請求的方法 method: 'get', // 默認值 // 若是url不是絕對路徑,那麼會將baseURL和url拼接做爲請求的接口地址 // 用來區分不一樣環境,建議使用 baseURL: 'https://some-domain.com/api/', // 用於請求以前對請求數據進行操做 // 只用當請求方法爲‘PUT’,‘POST’和‘PATCH’時可用 // 最後一個函數需return出相應數據 // 能夠修改headers transformRequest: [function (data, headers) { // 能夠對data作任何操做 return data; }], // 用於對相應數據進行處理 // 它會經過then或者catch transformResponse: [function (data) { // 能夠對data作任何操做 return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // URL參數 // 必須是一個純對象或者 URL參數對象 params: { ID: 12345 }, // 是一個可選的函數負責序列化`params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // 請求體數據 // 只有當請求方法爲'PUT', 'POST',和'PATCH'時可用 // 當沒有設置`transformRequest`時,必須是如下幾種格式 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // 請求超時時間(毫秒) timeout: 1000, // 是否攜帶cookie信息 withCredentials: false, // default // 統一處理request讓測試更加容易 // 返回一個promise並提供一個可用的response // 其實我並不知道這個是幹嗎的!!!! // (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. auth: { username: 'janedoe', password: 's00pers3cret' }, // 響應格式 // 可選項 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 默認值是json // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // 處理上傳進度事件 onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // 處理下載進度事件 onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // 設置http響應內容的最大長度 maxContentLength: 2000, // 定義可得到的http響應狀態碼 // return true、設置爲null或者undefined,promise將resolved,不然將rejected validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. // 最大重定向次數?沒用過不清楚 maxRedirects: 5, // 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 and port of the proxy server // 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`. // 代理 proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) // 用於取消請求?又是一個不知道怎麼用的配置項 cancelToken: new CancelToken(function (cancel) { }) } 

響應組成

response由如下幾部分信息組成

{
  // 服務端返回的數據 data: {}, // 服務端返回的狀態碼 status: 200, // 服務端返回的狀態信息 statusText: 'OK', // 響應頭 // 全部的響應頭名稱都是小寫 headers: {}, // axios請求配置 config: {}, // 請求 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'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 

實例默認配置

// 建立實例時修改配置 var instance = axios.create({ baseURL: 'https://api.example.com' }); // 實例建立以後修改配置 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 

配置優先級

配置項經過必定的規則合併,request config > instance.defaults > 系統默認,優先級高的覆蓋優先級低的。

// 建立一個實例,這時的超時時間爲系統默認的 0 var instance = axios.create(); // 經過instance.defaults從新設置超時時間爲2.5s,由於優先級比系統默認高 instance.defaults.timeout = 2500; // 經過request config從新設置超時時間爲5s,由於優先級比instance.defaults和系統默認都高 instance.get('/longRequest', { timeout: 5000 }); 

攔截器

你能夠在thencatch以前攔截請求和響應。

// 添加一個請求攔截器 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); }); // 添加一個響應攔截器 axios.interceptors.response.use(function (response) { // Do something with response data return response; }, function (error) { // Do something with response error return Promise.reject(error); }); 

若是以後想移除攔截器你能夠這麼作

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

你也能夠爲axios實例添加一個攔截器

var 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) { // 發送請求可是沒有響應返回 console.log(error.request); } else { // 其餘錯誤 console.log('Error', error.message); } console.log(error.config); }); 

你能夠用validateStatus定義一個http狀態碼返回的範圍.

axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } }) 

取消請求

你能夠經過cancel token來取消一個請求

The axios cancel token API is based on the withdrawn cancelable promises proposal.

You can create a cancel token using the CancelToken.source factory as shown below:

var CancelToken = axios.CancelToken; var source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); 

You can also create a cancel token by passing an executor function to the CancelToken constructor:

var CancelToken = axios.CancelToken; var 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(); 

Note: you can cancel several requests with the same cancel token.

Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

Browser

In a browser, you can use the URLSearchParams API as follows:

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

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Alternatively, you can encode data using the qs library:

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

Node.js

In node.js, you can use the querystring module as follows:

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

You can also use the qs library.

Semver

Until axios reaches a 1.0 release, breaking changes will be released with a new minor version. For example 0.5.1, and 0.5.4 will have the same API, but 0.6.0 will have breaking changes.

Promises

axios depends on a native ES6 Promise implementation to be supported.
If your environment doesn't support ES6 Promises, you can polyfill.

TypeScript

axios includes TypeScript definitions.

import axios from 'axios'; axios.get('/user?ID=12345'); 

Resources

Credits

axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular.

License

MIT

除了這二者外,還有一個代替ajax的庫,fetch,參見https://github.com/camsong/blog/issues/2。

相關文章
相關標籤/搜索