概要
Axios 是一個基于 Promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
特性
在瀏覽器中創(chuàng)建 XMLHttpRequests
在 node.js 則創(chuàng)建http請求
支持 Promise API
支持攔截請求和響應(yīng)
轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
取消請求
自動轉(zhuǎn)換JSON 數(shù)據(jù)
客戶端支持防御 XSRF
瀏覽器支持
支持Chrome、火狐、Edge、IE8+等瀏覽器
安裝
使用 npm安裝:
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n27" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">$ npm install axios -g</pre>
cdn引入
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n29" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><script src="https://unpkg.com/axios/dist/axios.min.js"></script></pre>
執(zhí)行 GET 請求
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n32" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 為給定 ID 的 user 創(chuàng)建請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
?
// GET 參數(shù)可以放到params里(推薦)
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
?
// 還可以使用ECMAScript 2017里的async/await,添加 async keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}</pre>
async/await 是 ECMAScript 2017新提供的功能 ,Internet Explorer 和一些舊的瀏覽器并不支持
執(zhí)行 POST 請求
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n36" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});</pre>
執(zhí)行多個并發(fā)請求
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n38" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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í)行完成
}));</pre>
axios API
可以通過向 axios 傳遞相關(guān)配置來創(chuàng)建請求
axios(config)
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n42" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 發(fā)送 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'))
});</pre>
axios(url[, config])
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n44" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 發(fā)送 GET 請求(默認的方法)
axios('/user/12345');</pre>
請求方法的別名
為方便使用,官方為所有支持的請求方法提供了別名,可以直接使用別名來發(fā)起請求:
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 這些屬性都不必在配置中指定。
并發(fā)
處理并發(fā)請求的助手函數(shù)
axios.all(iterable)
axios.spread(callback)
創(chuàng)建實例
可以使用自定義配置新建一個 axios 實例
axios.create([config])
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n63" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});</pre>
實例方法
以下是可用的實例方法。指定的配置將與實例的配置合并
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]])
請求配置項
下面是創(chuàng)建請求時可用的配置選項,注意只有 url 是必需的。如果沒有指定 method,請求將默認使用 get 方法。
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n75" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">{
// url 是用于請求的服務(wù)器 URL
url: "/user",
// method 是創(chuàng)建請求時使用的方法
method: "get", // 默認是 get
// 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) {
// 對 data 進行任意轉(zhuǎn)換處理
return data;
}],
// transformResponse 在傳遞給 then/catch 前,允許修改響應(yīng)數(shù)據(jù)
transformResponse: [function (data) {
// 對 data 進行任意轉(zhuǎn)換處理
return data;
}],
// headers 是即將被發(fā)送的自定義請求頭
headers: {"X-Requested-With": "XMLHttpRequest"},
// params 是即將與請求一起發(fā)送的 URL 參數(shù)
// 必須是一個無格式對象(plain object)或 URLSearchParams 對象
params: {
ID: 12345
},
// paramsSerializer 是一個負責 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, // 默認的
// adapter 允許自定義處理請求,以使測試更輕松
// 返回一個 promise 并應(yīng)用一個有效的響應(yīng) (查閱 response docs).
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", // 默認的
// 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 定義允許的響應(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; // 默認的
},
// maxRedirects 定義在 node.js 中 follow 的最大重定向數(shù)目
// 如果設(shè)置為0,將不會 follow 任何重定向
maxRedirects: 5, // 默認的
// httpAgent 和 httpsAgent 分別在 node.js 中用于定義在執(zhí)行 http 和 https 時使用的自定義代理。允許像這樣配置選項:
// keepAlive 默認沒有啟用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// "proxy" 定義代理服務(wù)器的主機名稱和端口
// auth 表示 HTTP 基礎(chǔ)驗證應(yī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) {
})
}</pre>
響應(yīng)結(jié)構(gòu)
axios請求的響應(yīng)包含以下信息:
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n78" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">{
// data 由服務(wù)器提供的響應(yīng)
data: {},
// status HTTP 狀態(tài)碼
status: 200,
// statusText 來自服務(wù)器響應(yīng)的 HTTP 狀態(tài)信息
statusText: "OK",
// headers 服務(wù)器響應(yīng)的頭
headers: {},
// config 是為請求提供的配置信息
config: {}
}</pre>
使用 then 時,會接收下面這樣的響應(yīng):
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n80" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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);
});</pre>
在使用 catch 時,或傳遞 rejection callback 作為 then 的第二個參數(shù)時,響應(yīng)可以通過 error 對象可被使用,正如在錯誤處理這一節(jié)所講。
配置的默認值/defaults
你可以指定將被用在各個請求的配置默認值
全局的 axios 默認值
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n85" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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";</pre>
自定義實例默認值
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n87" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 創(chuàng)建實例時設(shè)置配置的默認值
var instance = axios.create({
baseURL: "https://api.example.com"
});
// 在實例已創(chuàng)建后修改默認值
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;</pre>
配置的優(yōu)先級
配置會以一個優(yōu)先順序進行合并。
請求的config > 實例的 defaults 屬性 > 庫默認值:
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n91" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 使用由庫提供的配置的默認值來創(chuàng)建實例
// 此時超時配置的默認值是 0
var instance = axios.create();
// 覆寫庫的超時默認值
// 現(xiàn)在,在超時前,所有請求都會等待 2.5 秒
instance.defaults.timeout = 2500;
// 為已知需要花費很長時間的請求覆寫超時設(shè)置
instance.get("/longRequest", {
timeout: 5000
});</pre>
攔截器
可以自定義攔截器,在在請求或響應(yīng)被 then 或 catch 處理前攔截它們。
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n94" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 添加請求攔截器
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);
});</pre>
如果你想在稍后移除攔截器,可以這樣:
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n96" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var myInterceptor = axios.interceptors.request.use(function () {/.../});
axios.interceptors.request.eject(myInterceptor);</pre>
可以為自定義 axios 實例添加攔截器
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n98" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var instance = axios.create();
instance.interceptors.request.use(function () {/.../});</pre>
錯誤處理
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n100" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">axios.get("/user/12345")
.catch(function (error) {
if (error.response) {
// 請求已發(fā)出,但服務(wù)器響應(yīng)的狀態(tài)碼不在 2xx 范圍內(nèi)
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);
});</pre>
可以使用 validateStatus 配置選項定義一個自定義 HTTP 狀態(tài)碼的錯誤范圍。
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n102" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">axios.get("/user/12345", {
validateStatus: function (status) {
return status < 500; // 狀態(tài)碼在大于或等于500時才會 reject
}
})</pre>
取消請求
使用 cancel token 取消請求
Axios 的 cancel token API 基于cancelable promises proposal
可以使用 CancelToken.source 工廠方法創(chuàng)建 cancel token,像這樣:
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n108" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
}
});
axios.post('/user/5', {
name: 'new name'
}, {
cancelToken: source.token
})
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');</pre>
還可以通過傳遞一個 executor 函數(shù)到 CancelToken 的構(gòu)造函數(shù)來創(chuàng)建 cancel token:
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="javascript" cid="n110" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var CancelToken = axios.CancelToken;
var cancel;
axios.get("/user/12345", {
cancelToken: new CancelToken(function executor(c) {
// executor 函數(shù)接收一個 cancel 函數(shù)作為參數(shù)
cancel = c;
})
});
// 取消請求
cancel();</pre>
可以使用同一個 cancel token 取消多個請求