post請求能在url傳參嗎,axios二次封裝及調用,axios學習教程全攻略
axios 簡介
axios 是一個(ge)基于(yu)Promise 用(yong)于(yu)瀏覽器和(he) nodejs 的 HTTP 客戶(hu)端(duan),它(ta)本(ben)身具有以下特征:
從瀏(liu)覽器中(zhong)創(chuang)建 XMLHttpRequest
從 node.js 發出 http 請求
支(zhi)持 Promise API
攔截請求和響應
轉換請求和響應數據
取消請求
自(zi)動轉換JSON數據(ju)
客戶端支持(chi)防(fang)止 CSRF/XSRF
引入方式:
$ npm install axios
$ cnpm install axios //taobao源
$ bower install axios
或者使用cdn:
<script src="//unpkg.com/axios/dist/axios.min.js"></script>
舉個栗子:
執行 GET 請求
// 向具(ju)有(you)指定(ding)ID的用戶發出請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 也可以通(tong)過 params 對象(xiang)傳遞(di)參數
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) {
//兩個(ge)請求現已完成
}));
axios API
可(ke)以通過將相關(guan)配(pei)置傳(chuan)遞給 axios 來進行請求。
axios(config)
// 發送一(yi)個(ge) POST 請(qing)求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios(url[, config])
// 發送一個 GET 請求 (GET請求是(shi)默(mo)認請求模式)
axios('/user/12345');
請求方法別名
為(wei)了方便起見,已經(jing)為(wei)所有(you)支(zhi)持(chi)的請求方法(fa)提供了別名(ming)。
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]])
注意
當使用別名方法時,不需要在(zai)config中指定url,method和data屬(shu)性。
并發
幫助函(han)數處理并發請求。
axios.all(iterable)
axios.spread(callback)
創建實例
您可以使用自定義配置創(chuang)建axios的新實例。
axios.create([config])
var instance = axios.create({
baseURL: '//some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
實例方法
可用的實例方法如下所示。 指(zhi)定的配(pei)置(zhi)(zhi)將與實例配(pei)置(zhi)(zhi)合并。
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]])
請求配置
這(zhe)些是(shi)用于發出請求(qiu)的可用配置選項。 只有url是(shi)必(bi)需的。 如果未指(zhi)定(ding)方法,請求(qiu)將默(mo)認為GET。
{
// `url`是將用于請求的(de)服務器URL
url: '/user',
// `method`是發出請(qing)求(qiu)時使用的請(qing)求(qiu)方法
method: 'get', // 默認
// `baseURL`將被添(tian)加到(dao)`url`前面,除非(fei)`url`是絕對的。
// 可(ke)以方(fang)便(bian)地為(wei) axios 的實(shi)例設置`baseURL`,以便(bian)將相對 URL 傳遞給(gei)該實(shi)例的方(fang)法。
baseURL: '//some-domain.com/api/',
// `transformRequest`允許在請求數據(ju)發送(song)到(dao)服(fu)務(wu)器之(zhi)前對其(qi)進行更改(gai)
// 這只適用(yong)于請求方(fang)法'PUT','POST'和'PATCH'
// 數組中的最后一個(ge)(ge)函數必須返(fan)回一個(ge)(ge)字符串(chuan),一個(ge)(ge) ArrayBuffer或一個(ge)(ge) Stream
transformRequest: [function (data) {
// 做任何你想要的數據轉換
return data;
}],
// `transformResponse`允許在 then / catch之前對響應數據進行更改
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `headers`是要發(fa)送的自定(ding)義(yi) headers
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params`是要與(yu)請(qing)求一起(qi)發送的URL參數(shu)
// 必須(xu)是純對象或(huo)URLSearchParams對象
params: {
ID: 12345
},
// `paramsSerializer`是(shi)一(yi)個可選的(de)函(han)數,負責序列化`params`
// (e.g. //www.npmjs.com/package/qs, //api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data`是要(yao)作為請求(qiu)主體發(fa)送的(de)數據
// 僅適用于請(qing)求方法“PUT”,“POST”和“PATCH”
// 當沒有設置(zhi)`transformRequest`時,必須是以下類(lei)型之一(yi):
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
firstName: 'Fred'
},
// `timeout`指定(ding)請(qing)求超時(shi)之前的(de)毫秒數。
// 如(ru)果請求(qiu)的時間超過'timeout',請求(qiu)將被中止(zhi)。
timeout: 1000,
// `withCredentials`指(zhi)示是否跨站點訪問控制請求
// should be made using credentials
withCredentials: false, // default
// `adapter'允(yun)許自(zi)定義處(chu)理請求,這使得測(ce)試(shi)更容易。
// 返(fan)回一個promise并(bing)提供一個有效的響(xiang)應(參見[response docs](#response-api))
adapter: function (config) {
/* ... */
},
// `auth'表(biao)示應該使(shi)用 HTTP 基本(ben)認證,并提供(gong)憑據。
// 這將設置(zhi)一個`Authorization'頭,覆蓋任何(he)現有的`Authorization'自定義(yi)頭,使(shi)用`headers`設置(zhi)。
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// “responseType”表示(shi)服務器將響應的數據類型
// 包(bao)括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
//`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名稱
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName`是攜帶(dai)xsrf令牌值的http頭的名稱
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress`允(yun)許(xu)處理上傳的(de)進度事件(jian)
onUploadProgress: function (progressEvent) {
// 使用本地 progress 事件做(zuo)任何(he)你想(xiang)要做(zuo)的(de)
},
// `onDownloadProgress`允許處理(li)下載的進(jin)度事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `maxContentLength`定義允許的(de)http響應內容的(de)最大(da)大(da)小
maxContentLength: 2000,
// `validateStatus`定義是(shi)否解析(xi)或拒絕給定的(de)promise
// HTTP響應狀(zhuang)態(tai)碼(ma)。如果`validateStatus`返(fan)回`true`(或被(bei)設置為`null` promise將被(bei)解析;否則,promise將被(bei)
// 拒絕。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects`定義(yi)在node.js中要(yao)遵循(xun)的重(zhong)定向的最大數量。
// 如果設(she)置為0,則不會遵循重定向(xiang)。
maxRedirects: 5, // 默認
// `httpAgent`和`httpsAgent`用于定(ding)義(yi)在node.js中分別(bie)執(zhi)行http和https請求(qiu)時使(shi)用的自定(ding)義(yi)代理(li)。
// 允許(xu)配置類似`keepAlive`的選項,
// 默認情況下不(bu)啟用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy'定(ding)義代理服(fu)務器的主機名和端(duan)口
// `auth`表示(shi)HTTP Basic auth應該用(yong)于(yu)連接到(dao)代理,并(bing)提供credentials。
// 這將設置(zhi)一(yi)個`Proxy-Authorization` header,覆蓋任何(he)使用(yong)`headers`設置(zhi)的(de)現有的(de)`Proxy-Authorization` 自定義 headers。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// “cancelToken”指定(ding)可用(yong)于取(qu)消(xiao)請求的取(qu)消(xiao)令牌
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}
使(shi)用 then 時(shi),您將收到如(ru)下(xia)響(xiang)應:
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);
});
配置默認值
您可以指定將應用于每個請求的配置默(mo)認值。
全局axios默認值
axios.defaults.baseURL = '//api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
自定義實例默認值
//在創(chuang)建實例時設置配置默(mo)認值
var instance = axios.create({
baseURL:'//api.example.com'
});
//在實(shi)例(li)創建后改(gai)變默認值
instance.defaults.headers.common ['Authorization'] = AUTH_TOKEN;
配置優先級順序
配(pei)置將(jiang)與優先(xian)順(shun)序合并。 順(shun)序是(shi)(shi)lib / defaults.js中的庫(ku)默認值,然后是(shi)(shi)實例的defaults屬性,最后是(shi)(shi)請求的config參數。 后者將(jiang)優先(xian)于前者。 這里有一(yi)個例子。
//使(shi)用(yong)庫提供的配置(zhi)默認值創(chuang)建實例
//此時,超時配置值為(wei)`0`,這是庫的默(mo)認值
var instance = axios.create();
//覆蓋(gai)庫的超(chao)時默認值
//現在所有請求(qiu)將在超時前(qian)等待2.5秒
instance.defaults.timeout = 2500;
//覆蓋此請求的(de)超時,因為它知(zhi)道需要很長時間
instance.get('/ longRequest',{
timeout:5000
});
攔截器
你可以(yi)截取請求或響應在被 then 或者 catch 處理(li)之前
//添加請求攔截器
axios.interceptors.request.use(function(config){
//在(zai)發送請求之前做某事
return config;
},function(error){
//請求(qiu)錯誤時做些事(shi)
return Promise.reject(error);
});
//添加響應攔截器
axios.interceptors.response.use(function(response){
//對響應數(shu)據做些(xie)事
return response;
},function(error){
//請求錯誤時做些事
return Promise.reject(error);
});
如果(guo)你以后(hou)可能(neng)需要刪除攔截(jie)器。
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
你可(ke)以(yi)將攔截器添(tian)加到(dao)axios的自定義實(shi)例。
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
處理錯誤
axios.get('/ user / 12345')
.catch(function(error){
if(error.response){
//請求已發出,但服務器(qi)使用狀態代碼(ma)進(jin)行響應
//落在2xx的范(fan)圍之外
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
//在設(she)置(zhi)觸(chu)發錯誤的請求時發生了錯誤
console.log('Error',error.message);
}}
console.log(error.config);
});
您可(ke)以使用validateStatus配(pei)置(zhi)選項(xiang)定義(yi)自定義(yi)HTTP狀態碼錯誤范(fan)圍。
axios.get('/ user / 12345',{
validateStatus:function(status){
return status < 500; //僅當狀(zhuang)態代碼大于或(huo)等于500時拒絕
}}
})
消除
您可以使用取(qu)(qu)消(xiao)令(ling)牌取(qu)(qu)消(xiao)請(qing)求。
axios cancel token API基(ji)于(yu)可取消的promise提議,目前處于(yu)階段1。
您可(ke)以使(shi)用CancelToken.source工(gong)廠創建一個取(qu)消令牌,如下所示:
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 {
// 處理錯誤
}
});
//取(qu)消(xiao)請求(qiu)(消(xiao)息參數(shu)是可(ke)選(xuan)的(de))
source.cancel('操作(zuo)被用(yong)戶取消。');
您還(huan)可以通過(guo)將執行器函數(shu)傳遞給CancelToken構造(zao)函數(shu)來(lai)創建取消(xiao)令牌(pai):
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/ user / 12345',{
cancelToken:new CancelToken(function executor(c){
//一個執(zhi)行器函(han)數(shu)接(jie)收一個取(qu)消(xiao)函(han)數(shu)作為(wei)參(can)數(shu)
cancel = c;
})
});
// 取消請求
clear();
注(zhu)意:您可以使用(yong)相(xiang)同的取消(xiao)令牌取消(xiao)幾個請求。
使用(yong)application / x-www-form-urlencoded格(ge)式
默認(ren)情(qing)況下,axios將JavaScript對(dui)象序列化為JSON。 要以應用程序/ x-www-form-urlencoded格式發(fa)送數據,您可以使用以下選項之(zhi)一。
瀏覽器
在瀏覽器(qi)中(zhong),您可以使用(yong)URLSearchParams API,如下所示:
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
請注(zhu)意(yi),所有(you)瀏覽器(qi)都不(bu)支持URLSearchParams,但(dan)是(shi)有(you)一個polyfill可用(確保polyfill全局環境)。
或(huo)者,您可以使用qs庫對數據進(jin)行編碼:
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });
Node.js
在node.js中,可以使用querystring模塊,如(ru)下所示:
var querystring = require('querystring');
axios.post('//something.com/', querystring.stringify({ foo: 'bar' });
你也可(ke)以使用qs庫(ku)。
Promise
axios 依賴本機要支持ES6 Promise實(shi)現(xian)。 如果您的環境不(bu)支持ES6 Promises,您可以使用polyfill。
TypeScript
axios包(bao)括TypeScript定義。
import axios from 'axios';
axios.get('/user?ID=12345');
axios在很大程度(du)上受(shou)到Angular提供的$http服務的啟發。 最終,axios努力提供一個在Angular外使用的獨立(li)的$http-like服務。