中文文檔: http://www.axios-js.com/
npm 倉庫地址: https://www.npmjs.com/package/axios
github地址: https://github.com/axios/axios
簡介
axios是基于promise用于瀏覽器和node.js的http客戶端
- 1.支持瀏覽器和node.js
- 2.支持promise
- 3.能夠請求攔截和響應(yīng)
- 4.能轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
- 5.能取消請求
- 6.自動轉(zhuǎn)換為JSON數(shù)據(jù)
- 7.瀏覽器端支持防止CSRF(跨站請求偽造)
安裝
- 1.使用npm安裝
$ npm install axios
- 2.使用bower
$ bower install axios
- 3.使用CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
請求示例
- 1.發(fā)送GET請求
// 為給定 ID 的 user 創(chuàng)建請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的請求也可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
- 2.發(fā)送POST請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
- 3.執(zhí)行多個并發(fā)請求
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) {
// 兩個請求現(xiàn)在都執(zhí)行完成
}));
axios的API
- 1.
axios(config)
// 發(fā)送 POST 請求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios({
method: 'get',
url: 'https://cdn.gumt.top/blog_bg.jpg',
responseType: 'stream'
})
.then(res => {
res.data.pipe(fs.createWriteStream('blog_bg.jpg'))
})
我們甚至可以利用這個功能去做一些有趣的事情灵疮, 比如: 小型的爬蟲遍略。
- 2.
axios(url[,config])
// 發(fā)送一個GET請求(默認(rèn)的請求方式)
axios('/usre/123456');
并發(fā)請求
// iterable 一個可以迭代的參數(shù)如數(shù)組等
axios.all(iterable)
//callback要等到所有請求都完成才會執(zhí)行
axios.spread(callback)
請求方法別名
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]])
注意:我們使用別名方法去請求數(shù)據(jù)的時候, URL,Method,Data這個幾個參數(shù)不需要再配置中聲明烫罩。
創(chuàng)建一個axios實例
- 1.
axios.create([config])
let myFetch = axios.create({
baseURL:"https://some-domain.com/api/",
timeout:1000,
headers: {'X-Custom-Header':'foobar'}
})
- 2.實例方法
注意已定義的配置將和利用create創(chuàng)建的實例的配置合并
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]])
示例:
myFetch.get('getUser/1')
.then(res => {
console.log(res)
})
// 這里實際發(fā)起的是 https://some-domain.com/api/getUser/1 get請求。
請求配置
下面的請求配置項织咧, 只有URL是必須的蠕趁,如果method 請求方法沒有定義,那么它默認(rèn)是以GET的方式發(fā)出的請求鲜屏。
{
// `url` 是用于請求的服務(wù)器 URL
url: '/user',
// `method` 是創(chuàng)建請求時使用的方法
method: 'get', // default
// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL国拇。
// 它可以通過設(shè)置一個 `baseURL` 便于為 axios 實例的方法傳遞相對 URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允許在向服務(wù)器發(fā)送前洛史,修改請求數(shù)據(jù)
// 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
// 后面數(shù)組中的函數(shù)必須返回一個字符串,或 ArrayBuffer酱吝,或 Stream
transformRequest: [function (data, headers) {
// 對 data 進(jìn)行任意轉(zhuǎn)換處理
return data;
}],
// `transformResponse` 在傳遞給 then/catch 前也殖,允許修改響應(yīng)數(shù)據(jù)
transformResponse: [function (data) {
// 對 data 進(jìn)行任意轉(zhuǎn)換處理
return data;
}],
// `headers` 是即將被發(fā)送的自定義請求頭
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是即將與請求一起發(fā)送的 URL 參數(shù)
// 必須是一個無格式對象(plain object)或 URLSearchParams 對象
params: {
ID: 12345
},
// `paramsSerializer` 是一個負(fù)責(zé) `params` 序列化的函數(shù)
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` 是作為請求主體被發(fā)送的數(shù)據(jù)
// 只適用于這些請求方法 'PUT', 'POST', 和 'PATCH'
// 在沒有設(shè)置 `transformRequest` 時,必須是以下類型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 瀏覽器專屬:FormData, File, Blob
// - Node 專屬: Stream
data: {
firstName: 'Fred'
},
// `timeout` 指定請求超時的毫秒數(shù)(0 表示無超時時間)
// 如果請求話費了超過 `timeout` 的時間务热,請求將被中斷
timeout: 1000,
// `withCredentials` 表示跨域請求時是否需要使用憑證
withCredentials: false, // default
// `adapter` 允許自定義處理請求忆嗜,以使測試更輕松
// 返回一個 promise 并應(yīng)用一個有效的響應(yīng) (查閱 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示應(yīng)該使用 HTTP 基礎(chǔ)驗證,并提供憑據(jù)
// 這將設(shè)置一個 `Authorization` 頭崎岂,覆寫掉現(xiàn)有的任意使用 `headers` 設(shè)置的自定義 `Authorization`頭
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示服務(wù)器響應(yīng)的數(shù)據(jù)類型捆毫,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` 允許為上傳處理進(jìn)度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `onDownloadProgress` 允許為下載處理進(jìn)度事件
onDownloadProgress: function (progressEvent) {
// 對原生進(jìn)度事件的處理
},
// `maxContentLength` 定義允許的響應(yīng)內(nèi)容的最大尺寸
maxContentLength: 2000,
// `validateStatus` 定義對于給定的HTTP 響應(yīng)狀態(tài)碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設(shè)置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` 定義在 node.js 中 follow 的最大重定向數(shù)目
// 如果設(shè)置為0,將不會 follow 任何重定向
maxRedirects: 5, // default
// `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` 和 `httpsAgent` 分別在 node.js 中用于定義在執(zhí)行 http 和 https 時使用的自定義代理佛寿。允許像這樣配置選項:
// `keepAlive` 默認(rèn)沒有啟用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定義代理服務(wù)器的主機(jī)名稱和端口
// `auth` 表示 HTTP 基礎(chǔ)驗證應(yīng)當(dāng)用于連接代理濒憋,并提供憑據(jù)
// 這將會設(shè)置一個 `Proxy-Authorization` 頭娘纷,覆寫掉已有的通過使用 `header` 設(shè)置的自定義 `Proxy-Authorization` 頭。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` 指定用于取消請求的 cancel token
// (查看后面的 Cancellation 這節(jié)了解更多)
cancelToken: new CancelToken(function (cancel) {
})
}
響應(yīng)體結(jié)構(gòu)
{
data:{},
status:200,
//從服務(wù)器返回的http狀態(tài)文本
statusText:'OK',
//響應(yīng)頭信息
headers: {},
//`config`是在請求的時候的一些配置信息
config: {}
}
可以通過then
鏈?zhǔn)讲僮鳙@取響應(yīng)信息
axios.get('/user/12345')
.then(function(res){
console.log(res.data);
console.log(res.status);
console.log(res.statusText);
console.log(res.headers);
console.log(res.config);
})
配置默認(rèn)值
可以指定將被用在各個請求的配置默認(rèn)值
全局的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';
自定義實例默認(rèn)值
// 當(dāng)創(chuàng)建實例的時候配置默認(rèn)配置
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// 當(dāng)實例創(chuàng)建時候修改配置
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
配置優(yōu)先級
config配置將會以優(yōu)先級別來合并跋炕,順序是lib/defaults.js
中的默認(rèn)配置,然后是實例中的默認(rèn)配置律适,最后是請求中的config參數(shù)配置辐烂,越往后等級越高,后面的會覆蓋前面的例子捂贿。
//創(chuàng)建一個實例的時候會使用libray目錄中的默認(rèn)配置
//在這里timeout配置的值為0纠修,來自于libray的默認(rèn)值
var instance = axios.create();
//回覆蓋掉library的默認(rèn)值
//現(xiàn)在所有的請求都要等2.5S之后才會發(fā)出
instance.defaults.timeout = 2500;
//這里的timeout回覆蓋之前的2.5S變成5s
instance.get('/longRequest',{
timeout: 5000
});
攔截器
在請求或響應(yīng)被then或catch處理前攔截他們。
// 添加請求攔截器
axios.interceptors.request.use(function (config) {
// 在發(fā)送請求之前做些什么
return config;
}, function (error) {
// 對請求錯誤做些什么
return Promise.reject(error);
});
// 添加響應(yīng)攔截器
axios.interceptors.response.use(function (response) {
// 對響應(yīng)數(shù)據(jù)做點什么
return response;
}, function (error) {
// 對響應(yīng)錯誤做點什么
return Promise.reject(error);
});
如果你想要移除攔截器厂僧,可以進(jìn)行如下操作扣草。
var myInterceptor = axios.interceptor.request.use(function(){/*....*/});
axios.interceptors.request.eject(myInterceptor);
給自定義的axios實例添加攔截器
var myFetch = axios.create();
myFetch.interceptors.request.use(function(){}) // 請求攔截器
myFetch.interceptors.response.use(function(){}) // 響應(yīng)處理
示例:
let myFetch = axios({
baseURL: "http://192.168.0.100:8080/api/",
timeout: 5000
})
myFetch.interceptors.request.use(config => {
let token = localStorage.getItem("token");
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config;
}, error => {
return Promise.reject("Request failed");
})
/**
如果后端給我的數(shù)據(jù)格式如下:
{
status: xxx, // 狀態(tài)碼
msg: '', // 提示信息
data: [], // 響應(yīng)數(shù)據(jù)
success: true // 是否成功
}
*/
myFetch..interceptors.response.use(res => {
let {msg, status} = res.data;
console.lg(msg);
return res.data;
}, error => {
return Promise.reject("Error, The error could be a network exception or a system exception");
})
錯誤處理
axios.get('/user/12345')
.catch(function(error){
if(error.response){
//請求已經(jīng)發(fā)出,但是服務(wù)器響應(yīng)返回的狀態(tài)嗎不在2xx的范圍內(nèi)
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.header);
}else {
//一些錯誤是在設(shè)置請求的時候觸發(fā)
console.log('Error',error.message);
}
console.log(error.config);
});
取消請求
你可以通過一個cancel token來取消一個請求
你可以通過CancelToken.source工廠函數(shù)來創(chuàng)建一個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 {
//handle error
}
});
//取消請求(信息的參數(shù)可以設(shè)置的)
source.cance("操作被用戶取消");
你也可以給cancelToken構(gòu)造函數(shù)傳遞一個executor function來創(chuàng)建一個cancel token:
var cancelToken = axios.CancelToken;
var cance;
axios.get('/user/12345',{
cancelToken: new CancelToken(function(c){
//這個executor函數(shù)接受一個cancel function作為參數(shù)
cancel = c;
})
})
//取消請求
cancel();