原文地址:https://www.jianshu.com/p/27a5626973e4
Axios是一個基於promise的HTTP庫,可以用在瀏覽器和Node.js中。axios具有特徵:
- 從瀏覽器中創建 XMLHttpRequest
- 從 node.js 創建 http 請求
- 支持 Promise API
- 攔截請求和響應
- 轉換請求數據和響應數據
- 取消請求
- 自動轉換 JSON 數據
- 客戶端支持防禦 XSRF
安裝
使用npm:
$ npm install axios
使用bower:
$ bower install axios
使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
使用
1 執行GET請求
const axios = require('axios');
// 爲給定 ID 的 user 創建請求
axios.get('/user?ID=12345')
.then(function (response) {
// 成功處理
console.log(response);
})
.catch(function (error) {
// 失敗處理
console.log(error);
})
.then(function () {
// 總會執行
});
// 可選地,上面的請求可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// 總會執行
});
// 想使用 async/await 特性? 添加關鍵字`async`到你定義的函數/方法
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
async/await 是ECMAScript 2017的一部分,目前在IE和老版本的瀏覽器中不受支持
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');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 兩個請求現在都執行完成
}));
axios API
可以通過向 axios 傳遞相關配置來創建請求
axios(config)
// 發送 POST 請求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// 發送get請求圖片
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 請求(默認的方法)
axios('/user/12345');
請求方法的別名
爲方便起見,爲所有支持的請求方法提供了別名:
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.post(url[, data[, config]])
- axios.put(url[, data[, config]])
- axios.patch(url[, data[, config]])
在使用別名方法時,url、method、data 這些屬性都不必在配置中指定。
併發
幫助處理併發請求的幫助函數
- axios.all(iterable)
- axios.spread(callback)
創建實例
可以使用自定義配置新建一個 axios 實例
axios.create([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#post(url[, data[, config]])
- axios#put(url[, data[, config]])
- axios#patch(url[, data[, config]])
請求配置
這些是創建請求時可用的配置想選。只有 url 是必需的。如果沒有指定 method,請求將默認使用 get 方法。
{
// `url` 是用於請求的服務器 URL
url: '/user',
// `method` 是創建請求時使用的方法
method: 'get', // 默認是 get
// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。
// 它可以通過設置一個 `baseURL` 便於爲 axios 實例的方法傳遞相對 URLs
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允許在向服務器發送前,修改請求數據
// 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
// 後面數組中的函數必須返回一個字符串,或Buffer實例,或 ArrayBuffer,或FormData 或 Stream
// 你可能需要修改headers對象
transformRequest: [function (data) {
// 對 data 進行任意轉換處理
return data;
}],
// `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據
transformResponse: [function (data) {
// 對 data 進行任意轉換處理
return data;
}],
// `headers` 是即將被髮送的自定義請求頭
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是即將與請求一起發送的 URL 參數
// 必須是一個無格式對象(plain object)或 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', 和 'PATCH'
// 在沒有設置 `transformRequest` 時,必須是以下類型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 瀏覽器專屬:FormData, File, Blob
// - Node 專屬: Stream
data: {
firstName: 'Fred'
},
// `timeout` 指定請求超時的毫秒數
// 如果請求話費了超過 `timeout` 的時間,請求將被中斷
timeout: 1000, //(0 表示無超時時間)
// `withCredentials` 表示跨域請求時是否需要使用憑證
withCredentials: false, // 默認的
// `adapter` 允許自定義處理請求,以使測試更輕鬆
// 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據
// 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // 默認的
// `responseEncoding`表示用於響應的編碼
// 注意: 當responseType是stream時或者client-side請求時,配置無效
responseEncoding: 'utf8', // 默認的
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱
xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的
// `onUploadProgress` 允許爲上傳處理進度事件
onUploadProgress: function (progressEvent) {
// 對原生進度事件的處理
},
// `onDownloadProgress` 允許爲下載處理進度事件
onDownloadProgress: function (progressEvent) {
// 對原生進度事件的處理
},
// `maxContentLength` 定義允許的響應內容的最大尺寸
maxContentLength: 2000,
// `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設置爲 `null` 或 `undefined`),promise 將被 resolved; 否則,promise 將被 rejected
validateStatus: function (status) {
return status >= 200 && status < 300; // 默認的
},
// `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目
// 如果設置爲0,將不會 follow 任何重定向
maxRedirects: 5, // 默認的
// `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, // 默認的
// `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項:
// `keepAlive` 默認沒有啓用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定義代理服務器的主機名稱和端口
// 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` 表示 HTTP 基礎驗證應當用於連接代理,並提供憑據
// 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` 指定用於取消請求的 cancel token
// (查看後面的 Cancellation 這節瞭解更多)
cancelToken: new CancelToken(function (cancel) {
})
}
響應結構
某個請求的響應包含以下信息
{
// `data` 由服務器提供的響應
data: {},
// `status` 來自服務器響應的 HTTP 狀態碼
status: 200,
// `statusText` 來自服務器響應的 HTTP 狀態信息
statusText: 'OK',
// `headers` 服務器響應的頭
headers: {},
// `config` 是爲請求提供的配置信息
config: {}
}
使用 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 對象可被使用,正如在錯誤處理這一節所講。
配置默認值
你可以指定將被用在各個請求的配置默認值
1 全局的 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';
2 自定義實例默認值
// 創建實例時設置配置的默認值
var instance = axios.create({
baseURL: 'https://api.example.com'
});
// 在實例已創建後修改默認值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
3 配置的優先順序
配置會以一個優先順序進行合併。這個順序是:在 lib/defaults.js 找到的庫的默認值,然後是實例的 defaults 屬性,最後是請求的 config 參數。後者將優先於前者。這裏是一個例子:
// 使用由庫提供的配置的默認值來創建實例
// 此時超時配置的默認值是 `0`
var 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) {
// 對響應數據做點什麼
return response;
}, function (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 {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
可以使用 validateStatus 配置選項定義一個自定義 HTTP 狀態碼的錯誤範圍。
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // 狀態碼在大於或等於500時纔會 reject
}
})
取消
使用 cancel token 取消請求
Axios 的 cancel token API 基於cancelable promises proposal,它還處於第一階段。
可以使用 CancelToken.source 工廠方法創建 cancel token,像這樣:
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 {
// 處理錯誤
}
});
// 取消請求(message 參數是可選的)
source.cancel('Operation canceled by the user.');
還可以通過傳遞一個 executor 函數到 CancelToken 的構造函數來創建 cancel token:
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函數接收一個 cancel 函數作爲參數
cancel = c;
})
});
// 取消請求
cancel();
Note : 可以使用同一個 cancel token 取消多個請求
使用 application/x-www-form-urlencoded 格式
默認情況下,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);
注意,URLSearchParams並不被所有瀏覽器支持(查看caniuse.com),但是有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
在Node.js中,你可以使用querystring模塊,如下:
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
也可以選擇使用qs庫
語義版本
直到axios達到1.0版本,打破變化將用一個新的小版本發佈。例如0.5.1,0.5.4將有相同的API,但是0.6.0必須打破的變化。
Promises
axios取決於本地ES6承諾實現的支持。如果您的環境不支持ES6承諾,你可以polyfill
TypeScript
axios 包含了TypeScript定義
import axios from 'axios';
axios.get('/user?ID=12345');