前提條件:vue-cli 項目
安裝:
npm axios from 'axios'
較科學的封裝好的axios:(new-axios.js)
import axios from 'axios'
import { Notify } from 'vant';
// import Vue from 'vue'
// import store from '@/store' // 我此項目沒有用到vuex,所以vuex代碼的都注釋了,需要的自己打開使用
// import {ACCESS_TOKEN} from '@/store/mutation-types'
// 創建 axios 實例
const requests = axios.create({
baseURL: process.env.VUE_APP_API, // 基礎url,如果是多環境配置這樣寫,也可以像下面一行的寫死。
// baseURL: 'http://168.192.0.123',
timeout: 6000 // 請求超時時間
})
// 錯誤處理函數
const err = (error) => {
if (error.response) {
const data = error.response.data
// const token = Vue.ls.get(ACCESS_TOKEN)
if (error.response.status === 403) {
Notify({ type: 'danger', message: data.message||data.msg });
}
if (error.response.status === 401) {
Notify({ type: 'danger', message: '你沒有權限。' });
// if (token) {
// store.dispatch('Logout').then(() => {
// setTimeout(() => {
// window.location.reload()
// }, 1500)
// })
// }
}
}
return Promise.reject(error)
}
// request interceptor(請求攔截器)
requests.interceptors.request.use(config => {
// const token = Vue.ls.get(ACCESS_TOKEN)
const token = localStorage.getItem('token')
if (token) {
config.headers['token'] = token // 讓每個請求攜帶自定義 token 請根據實際情況自行修改
}
return config
}, err)
// response interceptor(接收攔截器)
requests.interceptors.response.use((response) => {
const res = response.data
if (res.code !== 0&&res.code!==200) {
Notify({ type: 'danger', message: res.message||res.msg });
// 401:未登錄;
if (res.code === 401||res.code === 403||res.code===999) {
Notify({ type: 'danger', message: '請登錄'});
}
return Promise.reject('error')
} else {
return res
}
}, err)
export default {
requests
}
main.js 引入,添加到vue原型
import requests from '@s/basejs/new-axios.js' // 記得改為你的路徑
Vue.prototype.rq = requests // 此處命名為rq,你可以改
使用
this.rq.get('/api/product/get?productChannelId='+this.productChannelId).then(res=>{ console.log(res) }) // 傳對象參數 // get請求記得加params this.rq.get('/api/product/get,{params:{name:'abc'}}).then(res=>{ console.log(res) }) this.rq.post('/api/product/get,{name:'abc'}).then(res=>{ console.log(res) })
以下步驟一般不需要
開發環境如果要跨域,解決跨域問題(設置代理):vue-cli 3.0的在 package.json 同級目錄新建一個 vue.config.js 文件,加入下面代碼,其他版本找到配置文件的devServer加入代碼
:
module.exports = { //axios域代理,解決axios跨域問題 baseUrl: '/', devServer: { proxy: { '': { target: 'http://192.168.0.108:8090', changeOrigin: true, ws: true, pathRewrite: { } } } } }
修改完后記得重啟項目應用配置
這博客是我博客園的第一篇博客,那時候剛出來工作,所以舊版封裝得有點爛,抱歉
基於這篇博客是我博客中評論最多的一篇(有點慘)所以下定決心改版一次(2020-3-13)
不懂的可以留言,我們一起探討
如果有幫助到你,希望你也能幫助下我,點下贊或者收藏