axios,vue-axios在项目中的应用
Axios 是一個(gè)基于 promise 的 HTTP 庫(kù),可以用在瀏覽器和 node.js 中
?
關(guān)于axios的功能:
1,從瀏覽器中創(chuàng)建XMLHttpRequests
2,從node.js常見Http請(qǐng)求
3,支持Promise API
4,攔截請(qǐng)求和響應(yīng)
5,轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
6,取消請(qǐng)求
7,自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)
8,客戶端支持防御XSRF
?
安裝:
使用node.js自帶的npm:
$ npm install axios?
如果是vue項(xiàng)目:
$ npm install vue-axios --save?
vue項(xiàng)目axios配置:
在mian.js中配置如下代碼:
import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios'Vue.use(VueAxios, axios)?
同也可以直接全局引入cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>?
GET:
?
axios.get('/user?ID=123').then( res => {// 請(qǐng)求數(shù)據(jù)成功并返回?cái)?shù)據(jù) console.info(res)}).catch( err => {if (e.response) {// 請(qǐng)求已發(fā)出,服務(wù)器返回狀態(tài)碼不是 2xx console.info(err.response.data)console.info(err.response.status)console.info(err.response.headers)} else if (err.request) {// 請(qǐng)求已發(fā)出,但沒有收到響應(yīng)// e.request 在瀏覽器里是一個(gè) XMLHttpRequest 實(shí)例// 在 node 中是一個(gè) http.ClientRequest 實(shí)例 console.info(err.request)} else {// 發(fā)送請(qǐng)求時(shí)異常,捕獲到錯(cuò)誤console.info('error', err.message)}console.info(err.config)})?// 等同于以下寫法 axios({url: '/user',methods: 'GET',params: {ID: 123}}).then(res => {console.info(res)}).catch(err => {console.info(err)})???????// 為給定 ID 的 user 創(chuàng)建請(qǐng)求axios.get('/user?ID=12345').then((response)=> {console.log(response);}).catch((error)=> {console.log(error);});?// 可選地,上面的請(qǐng)求可以這樣做axios.get('/user', {params: {ID: 12345}}).then((response)=> {console.log(response);}).catch((error)=> {console.log(error);});?
?
?
POST:
?
axios.post('/user', {firstName: 'Mike',lastName: 'Allen'}).then(res => {console.info(res)}).catch(err => {console.info(err)})?// 等同于以下寫法 axios({url: '/user',method: 'POST',data: {firstName: 'Mike',lastName: 'Allen'}}).then(res => {console.info(res)}).catch(err => {console.info(err)})??axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'}).then( (res)=> {console.log(res);}).catch( (err)=> {console.log(err);});?
?
?
?
執(zhí)行多個(gè)并發(fā)請(qǐng)求:
?
function getUserAccount() {return axios.get('/user/12345');}?function getUserPermissions() {return axios.get('/user/12345/permissions');}?axios.all([getUserAccount(), getUserPermission()]).then(axios.spread(function (acct, perms) {// 兩個(gè)請(qǐng)求現(xiàn)在都執(zhí)行完成}));?
?
?
注意事項(xiàng):
?
在使用?GET?方法傳遞參數(shù)時(shí)使用的是?params,并且官方文檔中介紹:
?
params are the URL parameters to be sent with the request. Must be a plain object or a URLSearchParams object.?
params?作為 URL 鏈接中的參數(shù)發(fā)送請(qǐng)求,且其必須是一個(gè)?plain object?或者是?URLSearchParams object?。
?
- plain object(純對(duì)象):是指?JSON?形式定義的普通對(duì)象或者?new Object()?創(chuàng)建的簡(jiǎn)單對(duì)象;
- URLSearchParams object:指的是一個(gè)可以由?URLSearchParams?接口定義的一些實(shí)用方法來(lái)處理 URL 的查詢字符串的對(duì)象,也就是說(shuō)?params?傳參是以?/user?ID=1&name=mike&sex=male?形式傳遞的。
?
而在使用?POST?時(shí)對(duì)應(yīng)的傳參使用的是?data,data?是作為?請(qǐng)求體?發(fā)送的,同樣使用這種形式的還有?PUT、PATCH?等請(qǐng)求方法。有一點(diǎn)需要注意的是,axios?中?POST?的默認(rèn)請(qǐng)求體類型為?Content-Type:application/json(JSON 規(guī)范流行),這也是最常見的請(qǐng)求體類型,也就是說(shuō)使用的是序列化后的?json?格式字符串來(lái)傳遞參數(shù),如:?{ "name" : "mike", "sex" : "male" };同時(shí),后臺(tái)必須要以支持?@RequestBody?的形式來(lái)接收參數(shù),否則會(huì)出現(xiàn)前臺(tái)傳參正確,后臺(tái)不接收的情況。
?
如果想要設(shè)置類型為?Content-Type:application/x-www-form-urlencoded(瀏覽器原生支持),axios?提供了兩種方式,如下:
?
?
?
瀏覽器端
const params = new URLSearchParams();params.append('param1', 'value1');params.append('param2', 'value2');axios.post('/user', params);不過(guò),并不是所有瀏覽器都支持?URLSearchParams,兼容性查詢caniuse.com,但是這里有一個(gè)Polyfill(polyfill:用于實(shí)現(xiàn)瀏覽器并不支持的原生 API 的代碼,可以模糊理解為補(bǔ)丁,同時(shí)要確保?polyfill?在全局環(huán)境中)
?
或者,你也可以用?qs?這個(gè)庫(kù)來(lái)格式化數(shù)據(jù),默認(rèn)情況下在安裝完?axios?后就可以使用?qs庫(kù)。
const qs = require('qs');axios.post('/user', qs.stringify({'name': 'mike'}));?
node 層
在?node?環(huán)境中可以使用?querystring?。同樣,也可以使用?qs?來(lái)格式化數(shù)據(jù)。
const querystring = require('querystring');axios.post('http://something.com/', querystring.stringify({'name':'mike'}));?
axios API
請(qǐ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])
在使用別名方法時(shí),url、methods、data?這些屬性都不必在配置中指定。
?
?
并發(fā)
axios.all(iterable) axios.spread(callback)創(chuàng)建實(shí)例
axios.create([config])var instance = axios.create({baseURL: 'https://something.com/api/',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}})
?
實(shí)例方法
- 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]])
?
請(qǐng)求配置
這些是創(chuàng)建請(qǐng)求時(shí)可以使用的配置選項(xiàng)。只有?url?是必需的,如果沒有指定的?method,請(qǐng)求將默認(rèn)使用?get?方法。
{// `url` 是用于請(qǐng)求的服務(wù)器 URLurl: '/user',?// `method` 是創(chuàng)建請(qǐng)求時(shí)使用的方法method: 'get', // 默認(rèn)是 get ?// `baseURL` 將自動(dòng)加在 `url` 前面,除非 `url` 是一個(gè)絕對(duì) URL。// 它可以通過(guò)設(shè)置一個(gè) `baseURL` 便于為 axios 實(shí)例的方法傳遞相對(duì) URLbaseURL: 'https://some-domain.com/api/',?// `transformRequest` 允許在向服務(wù)器發(fā)送前,修改請(qǐng)求數(shù)據(jù)// 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個(gè)請(qǐng)求方法// 后面數(shù)組中的函數(shù)必須返回一個(gè)字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data) {// 對(duì) data 進(jìn)行任意轉(zhuǎn)換處理 ?return data;}],?// `transformResponse` 在傳遞給 then/catch 前,允許修改響應(yīng)數(shù)據(jù) transformResponse: [function (data) {// 對(duì) data 進(jìn)行任意轉(zhuǎn)換處理 ?return data;}],?// `headers` 是即將被發(fā)送的自定義請(qǐng)求頭headers: {'X-Requested-With': 'XMLHttpRequest'},?// `params` 是即將與請(qǐng)求一起發(fā)送的 URL 參數(shù)// 必須是一個(gè)無(wú)格式對(duì)象(plain object)或 URLSearchParams 對(duì)象params: {ID: 12345},?// `paramsSerializer` 是一個(gè)負(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` 是作為請(qǐng)求主體被發(fā)送的數(shù)據(jù)// 只適用于這些請(qǐng)求方法 'PUT', 'POST', 和 'PATCH'// 在沒有設(shè)置 `transformRequest` 時(shí),必須是以下類型之一:// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - 瀏覽器專屬:FormData, File, Blob// - Node 專屬: Stream data: {firstName: 'Fred'},?// `timeout` 指定請(qǐng)求超時(shí)的毫秒數(shù)(0 表示無(wú)超時(shí)時(shí)間)// 如果請(qǐng)求話費(fèi)了超過(guò) `timeout` 的時(shí)間,請(qǐng)求將被中斷timeout: 1000,?// `withCredentials` 表示跨域請(qǐng)求時(shí)是否需要使用憑證withCredentials: false, // 默認(rèn)的 ?// `adapter` 允許自定義處理請(qǐng)求,以使測(cè)試更輕松// 返回一個(gè) promise 并應(yīng)用一個(gè)有效的響應(yīng) (查閱 [response docs](#response-api)). adapter: function (config) {/* ... */},?// `auth` 表示應(yīng)該使用 HTTP 基礎(chǔ)驗(yàn)證,并提供憑據(jù)// 這將設(shè)置一個(gè) `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', // 默認(rèn)的 ?// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱xsrfCookieName: 'XSRF-TOKEN', // default ?// `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱xsrfHeaderName: 'X-XSRF-TOKEN', // 默認(rèn)的 ?// `onUploadProgress` 允許為上傳處理進(jìn)度事件 onUploadProgress: function (progressEvent) {// 對(duì)原生進(jìn)度事件的處理 },?// `onDownloadProgress` 允許為下載處理進(jìn)度事件 onDownloadProgress: function (progressEvent) {// 對(duì)原生進(jìn)度事件的處理 },?// `maxContentLength` 定義允許的響應(yīng)內(nèi)容的最大尺寸maxContentLength: 2000,?// `validateStatus` 定義對(duì)于給定的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; // 默認(rèn)的 },?// `maxRedirects` 定義在 node.js 中 follow 的最大重定向數(shù)目// 如果設(shè)置為0,將不會(huì) follow 任何重定向maxRedirects: 5, // 默認(rèn)的 ?// `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ù)// 這將會(huì)設(shè)置一個(gè) `Proxy-Authorization` 頭,覆寫掉已有的通過(guò)使用 `header` 設(shè)置的自定義 `Proxy-Authorization` 頭。 proxy: {host: '127.0.0.1',port: 9000,auth: : {username: 'mikeymike',password: 'rapunz3l'}},?// `cancelToken` 指定用于取消請(qǐng)求的 cancel token// (查看后面的 Cancellation 這節(jié)了解更多)cancelToken: new CancelToken(function (cancel) {})}6 - 響應(yīng)結(jié)構(gòu) 某個(gè)請(qǐng)求的響應(yīng)包含以下信息:{// `data` 由服務(wù)器提供的響應(yīng) data: {},?// `status` 來(lái)自服務(wù)器響應(yīng)的 HTTP 狀態(tài)碼status: 200,?// `statusText` 來(lái)自服務(wù)器響應(yīng)的 HTTP 狀態(tài)信息statusText: 'OK',?// `headers` 服務(wù)器響應(yīng)的頭 headers: {},?// `config` 是為請(qǐng)求提供的配置信息 config: {}}使用?then?時(shí),你將接收下面這樣的響應(yīng):
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);});在使用?catch?時(shí),或傳遞?rejection callback?作為?then?的第二個(gè)參數(shù)時(shí),響應(yīng)可以通過(guò)?error?對(duì)象可被使用,正如在錯(cuò)誤處理這一節(jié)。
?全局的 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';?
自定義實(shí)例默認(rèn)值
// 創(chuàng)建實(shí)例時(shí)設(shè)置配置的默認(rèn)值var instance = axios.create({baseURL: 'https://api.example.com'});?// 在實(shí)例已創(chuàng)建后修改默認(rèn)值instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;?
配置的優(yōu)先順序
// 使用由庫(kù)提供的配置的默認(rèn)值來(lái)創(chuàng)建實(shí)例// 此時(shí)超時(shí)配置的默認(rèn)值是 `0`var instance = axios.create();?// 覆寫庫(kù)的超時(shí)默認(rèn)值// 現(xiàn)在,在超時(shí)前,所有請(qǐng)求都會(huì)等待 2.5 秒instance.defaults.timeout = 2500;?// 為已知需要花費(fèi)很長(zhǎng)時(shí)間的請(qǐng)求覆寫超時(shí)設(shè)置instance.get('/longRequest', {timeout: 5000});?
攔截器
在請(qǐng)求或響應(yīng)被?then?或?catch?處理前攔截它們// 添加請(qǐng)求攔截器 axios.interceptors.request.use(function (config) {// 在發(fā)送請(qǐng)求之前做些什么return config;}, function (error) {// 對(duì)請(qǐng)求錯(cuò)誤做些什么return Promise.reject(error);});?// 添加響應(yīng)攔截器 axios.interceptors.response.use(function (response) {// 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么return response;}, function (error) {// 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么return Promise.reject(error);});
如果你想在稍后移除攔截器,可以這樣:
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});axios.interceptors.request.eject(myInterceptor);可以為自定義 axios 實(shí)例添加攔截器:
var instance = axios.create();instance.interceptors.request.use(function () {/*...*/});?
??
轉(zhuǎn)載于:https://www.cnblogs.com/fengrenfan/p/10740495.html
總結(jié)
以上是生活随笔為你收集整理的axios,vue-axios在项目中的应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Django笔记06
- 下一篇: vue.$nextTick 解决了哪些问