創(chuàng)建日期: 2020年3月30日
axios版本: "^0.19.2"
GitHub文檔
Axios中文說明
題記:本篇文章抑进,大部分是摘自Axios中文說明,內(nèi)容有補(bǔ)充,順序有調(diào)整。如果想直接看項(xiàng)目中如何應(yīng)用咙俩,可直接跳至第十一部分和第四部分。
一.功能介紹
Axios 是一個基于 promise 的 HTTP 庫湿故,可以用在瀏覽器和 node.js 中阿趁。
功能:
- 從瀏覽器中創(chuàng)建 XMLHttpRequests
- 從 node.js 創(chuàng)建 http 請求
- 支持 Promise API
- 攔截請求和響應(yīng)
- 轉(zhuǎn)換請求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
- 取消請求
- 自動轉(zhuǎn)換 JSON 數(shù)據(jù)
- 客戶端支持防御 XSRF
瀏覽器支持:
Latest ?
|
image.png
|
Latest ?
|
Latest ?
|
Latest ?
|
Latest ?
|
---|---|---|---|---|---|
Latest ? | Latest ? | Latest ? | Latest ? | Latest ? | 8+ ? |
二.安裝
$ npm install axios --save-dev
三.簡單使用
測試網(wǎng)絡(luò)請求的網(wǎng)址: https://httpbin.org/
本來想寫一個測試用的網(wǎng)站,沒想到網(wǎng)上真是什么都有坛猪。福利了脖阵。
1.執(zhí)行Get請求
為什么放上了接口信息的截圖呢?乍一看這風(fēng)格墅茉,像及了swagger命黔。以后項(xiàng)目中會常用到,先放上來就斤,熟悉下悍募,也方便初學(xué)者理解。
import axios from 'axios'
//.....省略
axios({
method: 'get',
url: 'https://httpbin.org/get',
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
//.....省略
上面的例子中洋机,我們設(shè)置了請求方式即method坠宴,當(dāng)不設(shè)置的時(shí)候,默認(rèn)為get绷旗。
中文文檔中的例子:
// 獲取遠(yuǎn)端圖片
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
2.執(zhí)行Post請求
中文文檔中的例子:
// 發(fā)送 POST 請求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
3.全局的 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';
修改Get請求的例子喜鼓,如下:
axios.defaults.baseURL = 'https://httpbin.org/'
axios({
// method: 'get', 默認(rèn)為get,可以省略
url: 'get',
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
四.別名方法
為方便起見衔肢,為所有支持的請求方法提供了別名庄岖。
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í), url膀懈、method、data 這些屬性都不必在配置中指定谨垃。
1.執(zhí)行Get請求
axios.get('https://httpbin.org/get')
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
這個接口是個無參數(shù)接口启搂,不典型。
一般帶參數(shù)的接口刘陶,get方法會有兩種寫法胳赌,一種像上面那樣,將參數(shù)按格式拼接到url上匙隔,另一種疑苫,就是設(shè)置參數(shù),如下例:
// 為給定 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.執(zhí)行Post請求
以下這些例子來源于中文文檔
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
五. 并發(fā)
axios.all(iterable)
axios.spread(callback)
執(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í)行完成
}));
六. 創(chuàng)建實(shí)例及實(shí)例方法
1.創(chuàng)建實(shí)例
axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
2.實(shí)例方法
以下是可用的實(shí)例方法。指定的配置將與實(shí)例的配置合并捍掺。
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]])
3.配置 (axios API)
這些是創(chuàng)建請求時(shí)可以用的配置選項(xiàng)撼短。只有 url 是必需的。如果沒有指定 method挺勿,請求將默認(rèn)使用 get 方法曲横。
{
// `url` 是用于請求的服務(wù)器 URL
url: '/user',
// `method` 是創(chuàng)建請求時(shí)使用的方法
method: 'get', // default
// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL不瓶。
// 它可以通過設(shè)置一個 `baseURL` 便于為 axios 實(shí)例的方法傳遞相對 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` 時(shí),必須是以下類型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 瀏覽器專屬:FormData, File, Blob
// - Node 專屬: Stream
data: {
firstName: 'Fred'
},
// `timeout` 指定請求超時(shí)的毫秒數(shù)(0 表示無超時(shí)時(shí)間)
// 如果請求話費(fèi)了超過 `timeout` 的時(shí)間麦备,請求將被中斷
timeout: 1000,
// `withCredentials` 表示跨域請求時(shí)是否需要使用憑證
withCredentials: false, // default
// `adapter` 允許自定義處理請求孽椰,以使測試更輕松
// 返回一個 promise 并應(yīng)用一個有效的響應(yīng) (查閱 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示應(yīng)該使用 HTTP 基礎(chǔ)驗(yàn)證,并提供憑據(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 時(shí)使用的自定義代理削彬。允許像這樣配置選項(xiàng):
// `keepAlive` 默認(rèn)沒有啟用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定義代理服務(wù)器的主機(jī)名稱和端口
// `auth` 表示 HTTP 基礎(chǔ)驗(yàn)證應(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ōu)先順序
從上面的講解中壶笼,我們知道,配置有全局的 axios 默認(rèn)值和自定義實(shí)例默認(rèn)值,以及創(chuàng)建請求時(shí)候的配置雁刷。
配置會以一個優(yōu)先順序進(jìn)行合并覆劈。這個順序是:在 lib/defaults.js 找到的庫的默認(rèn)值,然后是實(shí)例的 defaults 屬性沛励,最后是請求的 config 參數(shù)责语。后者將優(yōu)先于前者。這里是一個例子:
// 使用由庫提供的配置的默認(rèn)值來創(chuàng)建實(shí)例
// 此時(shí)超時(shí)配置的默認(rèn)值是 `0`
var instance = axios.create();
// 覆寫庫的超時(shí)默認(rèn)值
// 現(xiàn)在目派,在超時(shí)前坤候,所有請求都會等待 2.5 秒
instance.defaults.timeout = 2500;
// 為已知需要花費(fèi)很長時(shí)間的請求覆寫超時(shí)設(shè)置
instance.get('/longRequest', {
timeout: 5000
});
八. 響應(yīng)結(jié)構(gòu)
某個請求的響應(yīng)包含以下信息:
{
// `data` 由服務(wù)器提供的響應(yīng)
data: {},
// `status` 來自服務(wù)器響應(yīng)的 HTTP 狀態(tài)碼
status: 200,
// `statusText` 來自服務(wù)器響應(yīng)的 HTTP 狀態(tài)信息
statusText: 'OK',
// `headers` 服務(wù)器響應(yīng)的頭
headers: {},
// `config` 是為請求提供的配置信息
config: {},
// 'request'
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}
}
1. .then
請求成功后,得到的響應(yīng)數(shù)據(jù)企蹭。
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);
});
2. .catch
請求失敗后白筹,得到的響應(yīng)數(shù)據(jù)智末。
錯誤處理
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
Y可以使用 validateStatus 配置選項(xiàng)定義一個自定義 HTTP 狀態(tài)碼的錯誤范圍。
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
九. 攔截器
在請求或響應(yīng)被 then 或 catch 處理前攔截它們徒河。
1.添加攔截器
// 添加請求攔截器
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ù)做點(diǎn)什么
return response;
}, function (error) {
// 對響應(yīng)錯誤做點(diǎn)什么
return Promise.reject(error);
});
2.移除攔截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
3.為自定義 axios 實(shí)例添加攔截器
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
十.取消
使用 cancel token 取消請求
Axios 的 cancel token API 基于cancelable promises proposal系馆,它還處于第一階段。
可以使用 CancelToken.source 工廠方法創(chuàng)建 cancel token虚青,像這樣:
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/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// 取消請求(message 參數(shù)是可選的)
source.cancel('Operation canceled by the user.');
還可以通過傳遞一個 executor 函數(shù)到 CancelToken 的構(gòu)造函數(shù)來創(chuàng)建 cancel token:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函數(shù)接收一個 cancel 函數(shù)作為參數(shù)
cancel = c;
})
});
// cancel the request
cancel();
注意: 可以使用同一個 cancel token 取消多個請求
十一.我在項(xiàng)目中的封裝使用
1.安裝
$ npm install axios --save-dev
2.使用
創(chuàng)建文件夾request它呀,在該文件夾里面創(chuàng)建文件index.js和文件夾interceptors。
在interceptors文件夾中棒厘,創(chuàng)建4個js文件纵穿,分別為:
requestInterceptor.js
requestErrorInterceptor.js
responseInterceptor.js
responseErrorInterceptor.js
開始寫代碼:
// src/request/requestInterceptor.js
export const requestErrorInterceptor = (error) => {
// do something if request error
console.log('requestErrorInterceptor')
console.log(error)
return error
}
//上面為箭頭函數(shù),下面為普通函數(shù)奢人,兩者都可
// export function requestErrorInterceptor(error) {
// // // do something if request error
// console.log('requestErrorInterceptor')
// //console.log(error)
// return error
// }
// src/request/requestErrorInterceptor.js
export const requestInterceptor = (config) => {
// do something before request
console.log('進(jìn)入RequestInterceptor')
return config
}
// src/request/responseInterceptor.js
export const responseInterceptor = (response) => {
// do something before response
console.log('進(jìn)入ResponseInterceptor')
return response.data
}
// src/request/responseErrorInterceptor.js
export const responseErrorInterceptor = (error) => {
console.log('進(jìn)入responseErrorInterceptor')
if (error.response) {
//do something
} else if (error.request) {
//do something
} else {
//do something
}
// do something if response error
throw error
//return error
}
四個攔截函數(shù)完成了谓媒,讓我們來實(shí)例化axios。
// src/request/index.js
import axios from 'axios'
import {requestInterceptor} from './interceptors/requestInterceptor'
import {requestErrorInterceptor} from './interceptors/requestErrorInterceptor'
import {responseInterceptor} from "./interceptors/responseInterceptor";
import {responseErrorInterceptor} from "./interceptors/responseErrorInterceptor";
const request = axios.create({
baseURL: 'https://httpbin.org/',
timeout: 30 * 1000,
})
request.interceptors.request.use(requestInterceptor, requestErrorInterceptor)
request.interceptors.response.use(responseInterceptor, responseErrorInterceptor)
export {request}
好了何乎,簡單的封裝已完成句惯。
我們來調(diào)用
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {request} from "./request";
const App = () => {
request.get('get')
.then((response) => {
console.log('進(jìn)入request.then方法')
})
.catch((error) => {
console.log(error)
})
return(
<h1>Hellow world!</h1>
)
}
ReactDOM.render(<App/>, document.getElementById('root'));
運(yùn)行后的輸出臺:
其他請求方式以及參數(shù)的添加,參看第四部分支救,別名函數(shù)里的實(shí)例抢野。
關(guān)于請求參數(shù)的上傳,多說兩句各墨。因?yàn)闇y試網(wǎng)頁的接口是無參數(shù)接口指孤,所以沒有展示傳參該如何寫。
一般get請求贬堵,我們會在url的參數(shù)后面恃轩,加上params參數(shù),該參數(shù)里面即是get請求方式所需要上傳的數(shù)據(jù)黎做;
Post方式叉跛,我們將參數(shù)寫在data里。
另外蒸殿,實(shí)際開發(fā)中筷厘,我們加了攔截,有些共通處理可以在response的攔截器里添加宏所,不需要每次請求都加then或者catch酥艳。
特別的,在項(xiàng)目中楣铁,我們通常會結(jié)合redux和saga來完成服務(wù)器請求數(shù)據(jù)方面的工作玖雁。
接下來更扁,筆者將逐一介紹redux和saga盖腕。最后將這三者結(jié)合赫冬,寫一個小demo,作為參考溃列。
其他文章:
React入門系列 目錄導(dǎo)引