vue專案詳解(2)- axios封裝及使用

### axios

#### axios 簡介

Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node。js 中。

vue專案詳解(2)- axios封裝及使用

#### axios 安裝

$ npm install axios

或者使用cdn

#### vue專案axios封裝

#### 建立資料夾並引用

* 建立axios。js資料夾

* 在 main。js 中引入。註冊到原型上。

* import https from “。/axios/axios。js”; //引入封裝的axios

* Vue。prototype。https = https; //引入到原型上。

* 使用 this。https。post() 因為是繫結在vue的原型上,所以用this就可以直接使用。

#### axios 的封裝

##### 在axios。js中引入axios

```

import axios from ‘axios’; // 引入axios

import QS from ‘qs’; // 引入qs模組,用來序列化post型別的資料,後面會提到

// vant的Message提示框元件,大家可根據自己的ui元件更改。

import { Message } from ‘element-ui’;

import router from “。。/router”; //引入,為了跳轉登入頁。

```

##### 請求超時設定

透過axios。defaults。timeout設定預設的請求超時時間。例如超過了10s,就會告知使用者當前請求超時,請重新整理等。

axios。defaults。timeout = 10000

##### 請求攔截器

我們在傳送請求前可以進行一個請求的攔截,那麼我們攔截請求是用來做什麼的呢?比如,有些請求是需要使用者登入之後才能訪問的,

或者post請求的時候,我們需要序列化我們提交的資料。這時候,我們可以在請求被髮送之前進行一個攔截,從而進行我們想要的操作。

```

axios。interceptors。request。use(

config => {

// 每次傳送請求之前判斷localStorage中是否存在登入的使用者資訊

// 如果存在,則統一在http請求的header都加上使用者資訊,這樣後臺根據使用者資訊判斷你的登入情況

// 即使本地存在token,也有可能token是過期的,所以在響應攔截器中要對返回狀態進行判斷

if (localStorage。getItem(‘Authorization’)) {

config。headers。Authorization = localStorage。getItem(‘Authorization’);

}

return config;

},

error => {

return Promise。error(error);

}

);

```

##### 響應攔截器

根據請求響應的資料及返回狀態碼,進行最基本的判斷;

axios。interceptors。response。use(

response => {

// 如果返回的狀態碼為200,說明介面請求成功,可以正常拿到資料

// 否則的話丟擲錯誤

if (response。status === 200) {

// if (response。data。statusCode == ‘10001’) {

// // 失敗時 跳轉登入頁

// router。push({

// path: “/login”

// });

// }

return Promise。resolve(response);

} else {

return Promise。reject(response);

}

},

// 伺服器狀態碼不是2開頭的的情況

// 這裡可以跟你們的後臺開發人員協商好統一的錯誤狀態碼

// 然後根據返回的狀態碼進行一些操作,例如未登入提示,錯誤提示等等

error => {

// 1。判斷請求超時

// if (error。code === ‘ECONNABORTED’ && error。message。indexOf(‘timeout’) !== -1) {

// console。log(‘根據你設定的timeout/真的請求超時 判斷請求現在超時了,你可以在這裡加入超時的處理方案’)

// return service。request(originalRequest);//例如再重複請求一次

// }

if (error。response。status) {

switch (error。response。status) {

// 401: 未登入

// 未登入則跳轉登入頁面,並攜帶當前頁面的路徑

// 在登入成功後返回當前頁面,這一步需要在登入頁操作。

case 401:

router。replace({

path: ‘/login’,

query: {

redirect: router。currentRoute。fullPath

}

});

break;

// 404請求不存在

case 404:

Message({

message: ‘網路請求不存在’,

duration: 1500,

forbidClick: true

});

break;

// 其他錯誤,直接丟擲錯誤提示

default:

Message({

message: error。response。data。message,

duration: 1500,

forbidClick: true

});

}

return Promise。reject(error。response);

}

}

);

##### get和post封裝

get方法:我們透過定義一個get函式,get函式有兩個引數,第一個引數表示我們要請求的url地址,第二個引數是我們要攜帶的請求引數。get函式返回一個promise物件,當axios其請求成功時resolve伺服器返回值,請求失敗時reject錯誤值。最後透過export丟擲get函式。

post方法:原理同get基本一樣,但是要注意的是,post方法必須要使用對提交從引數物件進行序列化的操作,所以這裡我們透過node的qs模組來序列化我們的引數。這個很重要,如果沒有序列化操作,後臺是拿不到你提交的資料的。這就是文章開頭我們import QS from ‘qs’;的原因。

```

// 封裝到一個物件中

let https = {

get(url, params) {

return new Promise((resolve, reject) => {

axios。get(url, {

params: params

})。then(res => {

resolve(res。data);

})。catch(err => {

reject(err。data)

})

})

},

post(url, params, json) {

let headers = {},

data;

headers[‘Content-type’] = json ? ‘application/json;charset=UTF-8’ : ‘application/x-www-form-urlencoded;charset=UTF-8’;

data = json ? params : QS。stringify(params);

return new Promise((resolve, reject) => {

axios。post(url, data, { headers: headers })

。then(res => {

resolve(res。data);

})

。catch(err => {

reject(err。data)

})

})

}

}

```

##### 輸出https

export default https;

### 專案中使用

```

login(){ // 驗證透過 登陸

this。https。get(‘/service’,{

data:{

command: ‘userLogin’,

platform: ‘web’,

account: this。utils。getAES(this。userName),

password: this。utils。getAES(this。password),

confirmLogin: ‘0’

}

})。then((res)=>{

if(res。statusCode == ‘10001’){

localStorage。clear(); // 清除所有的 localStorage;

localStorage。setItem(“Authorization”,res。data。token); //儲存token。

this。$router。push(“/organizerPage”)

}else if(res。statusCode == ‘10008’){

this。retreatPopup = true;

}else{

this。$message({

message: res。msg ,

type: ‘error’,

duration: 1000

});

}

})。catch((res)=>{

console。log(res);

})

},

```

#### 請求配置詳解

```

{

// `url` 是用於請求的伺服器 URL

url: ‘/user’,

// `method` 是建立請求時使用的方法

method: ‘get’, // 預設是 get

// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。

// 它可以透過設定一個 `baseURL` 便於為 axios 例項的方法傳遞相對 URL

baseURL: ‘https://some-domain。com/api/’,

// `transformRequest` 允許在向伺服器傳送前,修改請求資料

// 只能用在 ‘PUT’, ‘POST’ 和 ‘PATCH’ 這幾個請求方法

// 後面陣列中的函式必須返回一個字串,或 ArrayBuffer,或 Stream

transformRequest: [function (data) {

// 對 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, // 預設的

// `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’, // 預設的

// `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` 定義允許的響應內容的最大尺寸

maxContentLength: 2000,

// `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設定為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte

validateStatus: function (status) {

return status >= 200 && status < 300; // 預設的

},

// `maxRedirects` 定義在 node。js 中 follow 的最大重定向數目

// 如果設定為0,將不會 follow 任何重定向

maxRedirects: 5, // 預設的

// `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) {

})

}

```