1.常用封裝一(跟element-admin相同)
* 1.1在腳手架目錄utils目錄新建一個(gè)request.js 文件
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 300000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
if (store.getters.token) {
// let each request carry token
// ['X-Token'] is a custom headers key
// please modify it according to the actual situation
config.headers['token'] = getToken()
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
const res = response.data
// if the custom code is not 20000, it is judged as an error.
if (res.code !== '0000') {
Message({
message: res.msg || 'Error',
type: 'error',
duration: 5 * 1000
})
// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
if (res.code === '0002') {
store.dispatch('user/resetToken').then(() => {
// location.reload()
store.dispatch('user/logout')
router.push('/')
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
1.2 新建一個(gè)接口(api)目錄把每個(gè)模塊放到一個(gè)請(qǐng)求js文件里吏口,引用封裝的request.js
import request from '@/utils/request'
// 貨權(quán)轉(zhuǎn)移 插入
// business/ecargorightchange/{version}/insert
export function insertEcargorightchange(data) {
return request({
url: `/business/ecargorightchange/${version}/insert`,
method: 'post',
data: data
})
}
// 貨權(quán)轉(zhuǎn)移 更新
// api/business/ecargorightchange/{version}/update
export function upDateEcargorightchange(data) {
return request({
url: `/business/ecargorightchange/${version}/update`,
method: 'put',
data: data
})
}
// 根據(jù)ID 查詢貨權(quán)轉(zhuǎn)移
// business/ecargorightchange/123/querybyid?id=123123
export function getEcargorightchangeByid(data) {
return request({
url: `/business/ecargorightchange/${version}/querybyid`,
method: 'get',
params: data
})
}
2.常用封裝二
2.1首先,建立一個(gè)request.js文件,引入axios屡贺,可以在該文件中签钩,前端做請(qǐng)求攔截相應(yīng)、請(qǐng)求方式統(tǒng)一處理
- 安裝
cnpm install axios --save
2.2接下來(lái),創(chuàng)建axios實(shí)例
import axios from "axios"; //導(dǎo)入axios
export function request(config) {
const instance = axios.create({
baseURL: process.env.BASE_URL, // api base_url,
timeout: 60 * 1000, // 請(qǐng)求超時(shí)時(shí)間,
headers: { "Content-Type": "application/json" }, //請(qǐng)求頭
});
// 1.axios 攔截器
// 1.1請(qǐng)求攔截
instance.interceptors.request.use(config => {
return config
}, err => {
console.log(err)
})
//1.2響應(yīng)攔截
instance.interceptors.response.use(res => {
return res.data
}, err => {
console.log(err)
})
// 1.3發(fā)送網(wǎng)絡(luò)請(qǐng)求
return instance(config)
}
2.3 引入上面這個(gè)文件
import request from '@/utils/request'
// 貨權(quán)轉(zhuǎn)移 插入
// business/ecargorightchange/{version}/insert
export function insertEcargorightchange(data) {
return request({
url: `/business/ecargorightchange/${version}/insert`,
method: 'post',
data: data
})
}
二.案例
案例一:響應(yīng)攔截器異常狀態(tài)碼處理
service.interceptors.response.use(
response => {
if (response.status === 200) {
return Promise.resolve(response);
} else {
return Promise.reject(response);
}
},
// 服務(wù)器狀態(tài)碼不是200的情況
error => {
if (error.response.status) {
switch (error.response.status) {
// 401: 未登錄
// 未登錄則跳轉(zhuǎn)登錄頁(yè)面吱抚,并攜帶當(dāng)前頁(yè)面的路徑
// 在登錄成功后返回當(dāng)前頁(yè)面俺陋,這一步需要在登錄頁(yè)操作豁延。
case 401:
notification.error({
message: "請(qǐng)求失敗",
description: "登錄過期,請(qǐng)重新登錄"
});
axios.get('/relog').then(() => {
location.href = window.location.origin
})
break;
// 403 token過期
// 登錄過期對(duì)用戶進(jìn)行提示
// 清除本地token和清空vuex中token對(duì)象
// 跳轉(zhuǎn)登錄頁(yè)面
case 403:
notification.error({
message: "請(qǐng)求失敗",
description: "登錄過期腊状,請(qǐng)重新登錄"
});
break;
// 404請(qǐng)求不存在
case 404:
notification.error({
message: "請(qǐng)求失敗",
description: "網(wǎng)絡(luò)請(qǐng)求不存在"
});
break;
// 其他錯(cuò)誤诱咏,直接拋出錯(cuò)誤提示
default:
notification.error({
message: "請(qǐng)求失敗",
description: error.response.data.message
});
}
return Promise.reject(error.response);
}
}
);
案例二:分別對(duì)四種請(qǐng)求方式進(jìn)行封裝:url就是請(qǐng)求后端的地址,params是前端傳給后端的參數(shù)
注意
loginApi(data, config) {
return http.post('/zjport/user/login', data, config);
},
// 獲取本周某一天的菜譜以及評(píng)價(jià)接口
foodListApi(data, config) {
return http.get(`/zjport/weeklyFood/foodList`, { params: data }, config);
},
// get 如果這么封裝的話參數(shù)必須是對(duì)象 鍵名必須是params 不然發(fā)送不到參數(shù)
合并Get POST 請(qǐng)求
import axios from 'axios' //導(dǎo)入axios
import router from 'router'
export const baseURL = process.env.BASE_URL, // api base_url,
const instance = axios.create({
baseURL,
timeout: 60 * 1000, // 請(qǐng)求超時(shí)時(shí)間,
headers: {
'Content-Type': 'application/json'
}, //請(qǐng)求頭
})
// 添加多余請(qǐng)求頭
const headers = {
// 'X-token': '84cc8b79105c43708d1f4d65b952abf9',
// 'X-Token': getToken()
};
// 1.axios 攔截器
// 1.1請(qǐng)求攔截
instance.interceptors.request.use(
config => {
//添加toekn q權(quán)限
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
// 合并請(qǐng)求頭
Object.assign(config.headers, headers);
return config
},
err => {
return Promise.reject(err)
}
)
//1.2響應(yīng)攔截
instance.interceptors.response.use(
res => {
return res.data
},
err => {
//判斷權(quán)限 跳轉(zhuǎn)到登錄頁(yè)添加跳轉(zhuǎn)之前頁(yè)面的參數(shù)
if (err.response && err.response.status === 401) {
const fullPath = encodeURIComponent(router.currentRoute.value.fullPath) // 當(dāng)前路由地址
router.push('/login?redirectUrl=' + fullPath)
}
return Promise.reject(err)
}
)
// 1.3發(fā)送網(wǎng)絡(luò)請(qǐng)求
return instance(config)
// 導(dǎo)出請(qǐng)求工具函數(shù)
export default (url, method, submitData,config) => {
return instance({
url,
method,
[method.toLowerCase() === 'get' ? 'params' : 'data']: submitData,
config
})
}