Installing
npm install axios
Features 特征
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- 支持Promise的方法
- 攔截請求和響應(yīng)
- 轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
- 取消請求
- JSON數(shù)據(jù)的自動(dòng)轉(zhuǎn)換
- 客戶端支持防止XSRF攻擊
常用方法:
get:
axios.get('/user?ID=12345').then().catch();
或者
axios.get('/user', {
params: {
ID: 12345
}
}).then().catch
post:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then().catch()
并發(fā)請求:
function a(){
return axios.get('/x/1');
}
function b(){
return axios.get('/y/1');
}
axios.all([a(), b()]).then(axios.spread(function (acct, perms) {
// Both requests are now complete
}))
通過給axios傳遞配置發(fā)出請求
axios(config)
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
也可以是
axios(url[, config])
使用自定義配置創(chuàng)建axios的實(shí)例(用于封裝fetch)
axios.create([config])
Request Config有哪些選項(xiàng):
url:只有url是必須項(xiàng)
method:無特殊聲明是get
baseURL:除非url是絕對路徑,否則baseURL會(huì)在其前面,就是使用baseURL的時(shí)候,url可以方便的設(shè)置為相對路徑
transformRequest:在請求數(shù)據(jù)發(fā)送到服務(wù)器前對其進(jìn)行更改,這僅適用于請求方法“PUT”、“POST”和“PATCH”,還可以更改headers
transformRequest: [function (data, headers) {
// Do whatever you want to transform the data
return data;
}],
transformResponse:讓res在返回給then/catch前進(jìn)行更改
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
headers:是要發(fā)送的自定義頭
params:是與請求一起發(fā)送的URL參數(shù)
params: {
ID: 12345
},
paramsSerializer:是一個(gè)可選函數(shù),負(fù)責(zé)序列化'params'`
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
data:是作為請求主體發(fā)送的數(shù)據(jù),只支持“PUT”、“POST”和“PATCH”請求方式
data: {
firstName: 'Fred'
},
timeout:指定請求超時(shí)前的毫秒數(shù),超過超時(shí)時(shí)間,請求被中止
responseType: 'json', // default 服務(wù)器響應(yīng)的數(shù)據(jù)類型
responseEncoding: 'utf8', // default 解碼響應(yīng)的編碼
onUploadProgress:允許處理上載的進(jìn)度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
onDownloadProgress下載允許處理事件的進(jìn)度
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
maxContentLength:定義允許的http響應(yīng)內(nèi)容的最大大?。ㄒ宰止?jié)為單位)
maxContentLength: 2000,
validateStatus:定義是解析還是拒絕給定HTTP響應(yīng)狀態(tài)代碼的承諾。如果validateStatus返回true(或設(shè)置為null或undefined),則承諾將被解析;否則,承諾將被拒絕。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
maxRedirects: 5,// default 定義node.js中要遵循的最大重定向數(shù)。
httpAgent\httpsAgent:在node.js中分別定義執(zhí)行http和https請求時(shí)要使用的自定義代理。這允許添加默認(rèn)情況下未啟用的選項(xiàng),如“keepAlive”。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
proxy:定義代理服務(wù)器的主機(jī)名和端口。
cancelToken:取消令牌
Response Schema Response模式
請求的響應(yīng)對象中包含以下信息。
data: {},是服務(wù)器提供的響應(yīng)數(shù)據(jù)
status: 200,是服務(wù)器響應(yīng)中的HTTP狀態(tài)代碼
statusText: 'OK',是來自服務(wù)器響應(yīng)的HTTP狀態(tài)消息
headers: {},服務(wù)器響應(yīng)的標(biāo)頭
config: {},是為請求提供給“axios”的配置
request: {} request`是生成此響應(yīng)的請求
當(dāng)時(shí)用then方法時(shí)候,將要收到的響應(yīng)內(nèi)容
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默認(rèn)值:
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';
自定義axios實(shí)例默認(rèn)配置
const instance = axios.create({
baseURL: 'https://api.example.com'
});
配置的優(yōu)先順序:
配置將按優(yōu)先順序合并。順序是lib/defaults.js中的庫默認(rèn)值,然后是實(shí)例的defaults屬性,最后是請求的config參數(shù)。后者將優(yōu)先于前者
請求攔截器和響應(yīng)攔截器的處理
// Add a request interceptor 處理的是config
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 處理的是res
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
如果需要給axios 的實(shí)例加上攔截器
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
使用application/x-www-form-urlencoded格式:
默認(rèn)情況下,axios將JavaScript對象序列化為JSON。要改為以application/x-www-form-urlencoded格式發(fā)送數(shù)據(jù),可以使用qs庫對數(shù)據(jù)進(jìn)行編碼:
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
axios是基于es6的Promise實(shí)現(xiàn)的