總結(jié):vue中Axios的封裝-API接口的管理

vue中axios的封裝

在vue項(xiàng)目和后端交互獲取數(shù)據(jù)時(shí),通常使用axios庫,官方文檔

淺談在項(xiàng)目中axios的簡單二次封裝

安裝

npm install axios; //安裝axios

//cnpm install axios;//或者使用鏡像下載.

#### 引入組件

**通常情況下,在項(xiàng)目src目錄下創(chuàng)建request文件夾,然后創(chuàng)建http.js和api.js文件。**

- http.js用來二次封裝axios;

-? api.js用來統(tǒng)一管理后端接口;

**在http.js文件中**

- 引入axios;

- 引入qs,用于序列化post類型的數(shù)據(jù)。

- 引入ui提示框,根據(jù)自己u進(jìn)行修改;**[推薦elementui文檔]**



?環(huán)境切換

在http.js的文件中的axios.defaults.baseURL可以設(shè)置axios的默認(rèn)請求地址。配合不同的運(yùn)行指令進(jìn)行開發(fā)不同環(huán)境的數(shù)據(jù)。

另附配置[vue不同環(huán)境配置不同打包命令]

// 環(huán)境的切換

if (process.env.NODE_ENV == 'development') {? ?

? ? axios.defaults.baseURL = 'https://www.baidu.com';}

else if (process.env.NODE_ENV == 'debug') {? ?

? axios.defaults.baseURL = 'https://www.ceshi.com';

}

else if (process.env.NODE_ENV == 'production') {? ?

? ? ? axios.defaults.baseURL = 'https://www.production.com';

}

請求默認(rèn)值的設(shè)置

**通過axios.defaults.timeout設(shè)置默認(rèn)的請求超時(shí)時(shí)間。**

//設(shè)置默認(rèn)的請求超時(shí)時(shí)間

axios.defaults.timeout = 10000;

**設(shè)置默認(rèn)請求頭和token**

//設(shè)置post的請求頭

axios.defaults.headers.post['Content-Type'] = 'application/json';

//設(shè)置默認(rèn)token 一般有權(quán)限不在這里設(shè)置

//axios.defaults.headers.Authorization=token;

請求攔截

**token攔截**

一般情況下,發(fā)送請求必須帶有token進(jìn)行驗(yàn)證。做權(quán)限的話這里需要注意。

axios.interceptors.request.use(

config => {

? ? let token = localStorage.getItem("header");

? ? if (token) {? // 判斷是否存在token,如果存在的話,則每個(gè)http header都加上token

? ? ? config.headers.token = `${token}`;

? ? }

? ? return config;

? },

? err => {

? ? this.$router.push("/login")

? ? return Promise.reject(err);

? });


**響應(yīng)攔截**

*這里需要根據(jù)后端協(xié)商,根據(jù)后端返回狀態(tài)碼進(jìn)行處理*


axios.interceptors.response.use(function (response) {

? if (response.status >= 400) {

? ? localStorage.clear();// 刪除已經(jīng)失效或過期的token(不刪除也可以,因?yàn)榈卿浐蟾采w)

? ? router.replace({

? ? ? path: '/login', // 到登錄頁重新獲取token

? ? ? query: {

? ? ? //回到當(dāng)前頁面

? ? ? ? redirect: router.currentRoute.fullPath

? ? }

? ? })

? }

? return response

}, function (error) {

? if (error.response) {

? ? if(error.response.status===403){

? ? Message({

? ? ? ? showClose: true,

? ? ? ? message: '登錄過期',

? ? ? ? type: 'error'

? ? });

? ? ? ? localStorage.clear();

? ? ? ? Cookies.set("user","",-10);

? ? ? ? router.replace({

? ? ? ? ? path: '/login' // 到登錄頁重新獲取token

? ? ? ? })

? ? }else if(error.response.status===405){

? ? ? Message({

? ? ? ? showClose: true,

? ? ? ? message: '權(quán)限不足,請聯(lián)系管理員',

? ? ? ? type: 'warning'

? ? });

? ? router.replace({

? ? path: '/error',

? ? })

? ? }else if(error.response.status===500){

? ? ? Message({

? ? ? ? showClose: true,

? ? ? ? message: '服務(wù)器異常',

? ? ? ? type: 'error'

? });

? ? }

? ? }

? return Promise.reject(error)

})

封裝get和post方法

*axios封裝的方法有很多,比如get,post,delete,put等方法。這里簡單介紹get和post的封裝。*

**post**

/**

* post方法,對應(yīng)post請求

* @param {String} url [請求的url地址]

* @param {Object} params [請求時(shí)攜帶的參數(shù)]

*/

export function post(url, params) {

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

? ? ? ? axios.post(url, params)

? ? ? ? ? ? .then(res => {

? ? ? ? ? ? ? ? resolve(res.data);

? ? ? ? ? ? })

? ? ? ? ? ? .catch(err => {

? ? ? ? ? ? ? ? reject(err.data)

? ? ? ? ? ? })

? ? });

}

**get**

/**

* get方法,對應(yīng)get請求

* @param {String} url [請求的url地址]

* @param {Object} params [請求時(shí)攜帶的參數(shù)]

*/

export function get(url, params) {

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

? ? ? ? axios.get(url, {

? ? ? ? ? ? params: params

? ? ? ? }).then(res => {

? ? ? ? ? ? resolve(res.data);

? ? ? ? }).catch(err => {

? ? ? ? ? ? reject(err.data)

? ? ? ? })

? ? });

}

vue中api的封裝

*首先在api.js中引入在http.js中封裝的get和post兩種方法。*

import { get, post } from './http'

*不同參數(shù)的封裝接口方法*

export const Login = p => get('/api/admin/login', p);

export const Registry = p => post('/api/admin/registry', p);

//路徑參數(shù)封裝

//export const? Api= p => post('/api/'+ p);

//多參數(shù)封裝

export const? Api=( p,q )=> post('/api/'+ p+“/"+q);

*頁面中使用方法*

import { Login,Registry } from "@/request/api"

export default {

name:"app",

data(){

return{

message:{

uname:"",

upwd:""

}

}

},

methods:{

login(){

Login(this.message).then(res=>{

....請求成功的處理

})

}

}

}

例外附上:

1.[gulp安裝與使用]

2.[搭建基于webpack的vue環(huán)境]

3.[淺談Vue項(xiàng)目優(yōu)化心得]

4.[總結(jié):搭建Vue項(xiàng)目心得]

5. [總結(jié):vue中Axios的封裝-API接口的管理]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。