前言
前端程序與服務器通信的最常見方式是通過HTTP協議。在我們沒有接觸 React、Angular、Vue 這類 MVVM 的前端框架之前, Jquery 除了優秀的前端 DOM 元素操作性以外,它的$.ajax()函數還能夠非常便捷的發起 http 請求?,F在我們已經開始使用 MVVM框架進行前端開發,拋棄了對頁面 DOM 元素的操作,難道為了方便的發起 http 請求,還需要在項目中加載 jquery 或者是手動創建 http 請求嗎?答案當然是不用的,隨著 Vue 作者尤雨溪宣布不再維護 vue-resource,轉而推薦大家使用 axios,目前在 Vue 社區中 axios 開始占據 http 庫的主導地位,所以這一章我們就介紹下如何使用 axios 發起 http 請求。
一、axios
Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中
二、特點
- 支持從瀏覽器中創建 XMLHttpRequests
- 支持從 node.js 創建 http 請求
- 支持 Promise API
- 能攔截請求和響應
- 能轉換請求數據和響應數據
- 能取消請求
- 自動轉換 JSON 數據
- 客戶端支持防御 XSRF
三、安裝
// 使用 npm 安裝
npm install axios
// 使用 bower安裝
bower install axios
// 使用 cdn 引入
< script src = "https://unpkg.com/axios/dist/axios.min.js" ></script>
四、例子
【1】發送一個 get請求
// 通過給定的ID來發送請求
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】發送一個POST
請求
axios.post('/user',{
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
【3】同時發起多個請求
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) {
// 當這兩個請求都完成的時候會觸發這個函數,兩個參數分別代表返回的結果
}));
五、axios的API
axios可以通過配置(config
)來發送請求
【1】axios(config)
// 發送一個 POST 請求
axios({
method: 'POST',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// 獲取遠程圖片
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
【2】axios(url[, config])
// 發起一個GET請求(GET是默認的請求方法)
axios('/user/12345');
六、請求方法別名
為了方便,為所有支持的請求方法均提供了別名。當使用別名方法時,url,method和data等屬性不用在config重復聲明
axios.request(url);
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]]);
七、并發(Concurrency)
以下兩個用來處理同時發生多個請求的輔助函數
// iterable是一個可以迭代的參數,如數組等
axios.all(iterable)
// callback要等到所有請求都完成才會執行
axios.spread(callback)
八、創建實例
可以使用自定義配置新建一個 axios 實例 axios.create([config])
let instance = axios.cerate({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header':'foobar'}
});
九、實例方法
以下是所有可用的實例方法,額外聲明的配置將與利用create創建的實例配置合并
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]])
十、請求的配置(request config)
這些是創建請求時可以用的配置選項。只有 url 是必需的。如果沒有指定 method,請求將默認使用 get 方法。
{
// url 是用于請求的服務器 URL
url: '/user',
// method 是創建請求時使用的方法
method: 'get', // default
// baseURL 將自動加在 url 前面,除非 url 是一個絕對 URL。
// 它可以通過設置一個 baseURL 便于為 axios 實例的方法傳遞相對 URL
baseURL: 'https://some-domain.com/api/',
// transformRequest 允許在向服務器發送前,修改請求數據
// 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
// 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data, headers) {
// 對 data 進行任意轉換處理
return data;
}],
// transformResponse 在傳遞給 then/catch 前,允許修改響應數據
transformResponse: [function (data) {
// 對 data 進行任意轉換處理
return data;
}],
// headers 是即將被發送的自定義請求頭
headers: { 'X-Requested-With': 'XMLHttpRequest' },
// params 是即將與請求一起發送的 URL 參數
// 必須是一個無格式對象(plain object)或 URLSearchParams 對象
params: {
ID: 12345
},
// paramsSerializer 是一個負責 params 序列化的函數
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, { arrayFormat: 'brackets' })
},
// data 是作為請求主體被發送的數據
// 只適用于這些請求方法 'PUT', 'POST', 和 'PATCH'
// 在沒有設置 transformRequest 時,必須是以下類型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 瀏覽器專屬:FormData, File, Blob
// - Node 專屬: Stream
data: {
firstName: 'Fred'
},
// timeout 指定請求超時的毫秒數(0 表示無超時時間)
// 如果請求話費了超過 timeout 的時間,請求將被中斷
timeout: 1000,
// withCredentials 表示跨域請求時是否需要使用憑證
withCredentials: false, // default
// adapter 允許自定義處理請求,以使測試更輕松
// 返回一個 promise 并應用一個有效的響應 (查閱 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// auth 表示應該使用 HTTP 基礎驗證,并提供憑據
// 這將設置一個 Authorization 頭,覆寫掉現有的任意使用 headers 設置的自定義 Authorization頭
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// responseType 表示服務器響應的數據類型,可以是 '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 允許為上傳處理進度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// onDownloadProgress 允許為下載處理進度事件
onDownloadProgress: function (progressEvent) {
// 對原生進度事件的處理
},
// maxContentLength 定義允許的響應內容的最大尺寸
maxContentLength: 2000,
// validateStatus 定義對于給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 validateStatus 返回 true (或者設置為 null 或 undefined),promise 將被 resolve; 否則,promise 將被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// maxRedirects 定義在 node.js 中 follow 的最大重定向數目
// 如果設置為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 中用于定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項:
// keepAlive 默認沒有啟用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定義代理服務器的主機名稱和端口
// auth 表示 HTTP 基礎驗證應當用于連接代理,并提供憑據
// 這將會設置一個 Proxy-Authorization 頭,覆寫掉已有的通過使用 header 設置的自定義 Proxy-Authorization 頭。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// cancelToken 指定用于取消請求的 cancel token
// (查看后面的 Cancellation 這節了解更多)
cancelToken: new CancelToken(function (cancel) {
})
}
十一、響應組成(請求返回的內容)
response由以下幾部分信息組成
{
// data 由服務器提供的響應
data: {},
// status 來自服務器響應的 HTTP 狀態碼
status: 200,
// statusText 來自服務器響應的 HTTP 狀態信息
statusText: 'OK',
// headers 服務器響應的頭
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: {}
}
使用 then
時,你將接收下面這樣的響應
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);
})
十二、默認配置值
你可以指定將被用在各個請求的配置默認值
【1】全局修改axios默認配置
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';
【2】自定義實例默認設置
// 創建實例時修改配置
var instance = axios.create({
baseURL: 'https://api.example.com'
});
// 實例創建之后修改配置
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
【3】配置的優先級
配置會以一個優先順序進行合并。這個順序是:在 lib/defaults.js 找到的庫的默認值,然后是實例的 defaults 屬性,最后是請求的 config 參數。后者將優先于前者
// 創建一個實例,這時的超時時間為系統默認的 0
var instance = axios.create();
// 通過instance.defaults重新設置超時時間為2.5s,因為優先級比系統默認高
instance.defaults.timeout = 2500;
// 通過request config重新設置超時時間為5s,因為優先級比instance.defaults和系統默認都高
instance.get('/longRequest', {
timeout: 5000
});
十三、攔截器
可以在then和catch之前攔截請求和響應
// 添加請求攔截器
axios.interceptors.request.use(function (config) {
// 在發送請求之前做些什么
return config;
}, function (error) {
// 對請求錯誤做些什么
return Promise.reject(error);
});
// 添加響應攔截器
axios.interceptors.response.use(function (response) {
// 對響應數據做點什么
return response;
}, function (error) {
// 對響應錯誤做點什么
return Promise.reject(error);
});
移除攔截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
為axios實例添加一個攔截器
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
十四、錯誤處理
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// 發送請求后,服務端返回的響應碼不是 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 發送請求但是沒有響應返回
console.log(error.request);
} else {
// 其他錯誤
console.log('Error', error.message);
}
console.log(error.config);
});
可以用 validateStatus 定義一個http狀態碼返回的范圍
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500;
}
})
十五、取消請求
可以通過cancel token來取消一個請求
可以通過CancelToken.source工廠函數來創建一個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 參數是可選的)
source.cancel('Operation canceled by the user.');
還可以通過傳遞一個 executor 函數到 CancelToken 的構造函數來創建 cancel token
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函數接收一個 cancel 函數作為參數
cancel = c;
})
});
// cancel the request
cancel();
十六、vue中Axios的封裝
原文:https://juejin.cn/post/6844903652881072141
十七、參考
axios中文文檔: http://www.axios-js.com/zh-cn/docs/
文章每周持續更新,可以微信搜索「 前端大集錦 」第一時間閱讀,回復【視頻】【書籍】領取200G視頻資料和30本PDF書籍資料