Vue二次封裝axios流程詳解
一、為什么要封裝axios
api統(tǒng)一管理,不管接口有多少,所有的接口都可以非常清晰,容易維護。
通常我們的項目會越做越大,頁面也會越來越多,如果頁面非常的少,直接用axios也沒有什么大的影響,那頁面組件多了起來,上百個接口呢,這個時候后端改了接口,多加了一個參數(shù)什么的呢?那就只有找到那個頁面,進去修改,整個過程很繁瑣,不易于項目的維護和迭代。
這個時候如果我們統(tǒng)一的區(qū)管理接口,需要修改某一個接口的時候直接在api里修改對應的請求,是不是很方便呢?因為我們用的最多的還是get post請求,我們就可以針對封裝。
二、怎么封裝axios
1. 拿到項目和后端接口,首先要配置全局代理;
2. 接著全局封裝axios和request.js;
3. 過濾axios請求方式,控制路徑,參數(shù)的格式,http.js;
4. 正式封裝api.js;
5. 頁面調(diào)用;
三、具體步驟
vue項目的前期配置
1. 終端輸入
npm i axios -S
2. 在項目中 main.js 文件中輸入
import axios from "axios";
配置config文件中的代理地址
修改項目中config目錄下的index.js文件?!疽部赡苁莢ue.config.js 文件】
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/': {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: {
'^/': ''
}
},
'/ws/*': {
target: 'ws://127.0.0.1:8080',
ws: true
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8082, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}封裝axios實例-request.js
/**** request.js ****/
// 導入axios
import axios from 'axios'
// 使用element-ui Message做消息提醒
import { Message} from 'element-ui';
//1. 創(chuàng)建新的axios實例,
const service = axios.create({
// 公共接口--這里注意后面會講
baseURL: process.env.BASE_API,
// 超時時間 單位是ms,這里設置了3s的超時時間
timeout: 3 * 1000
})
// 2.請求攔截器
service.interceptors.request.use(config => {
//發(fā)請求前做的一些處理,數(shù)據(jù)轉(zhuǎn)化,配置請求頭,設置token,設置loading等,根據(jù)需求去添加
config.data = JSON.stringify(config.data); //數(shù)據(jù)轉(zhuǎn)化,也可以使用qs轉(zhuǎn)換
config.headers = {
'Content-Type':'application/json' //配置請求頭
}
//如有需要:注意使用token的時候需要引入cookie方法或者用本地localStorage等方法,推薦js-cookie
//const token = getCookie('名稱');//這里取token之前,你肯定需要先拿到token,存一下
//if(token){
//config.params = {'token':token} //如果要求攜帶在參數(shù)中
//config.headers.token= token; //如果要求攜帶在請求頭中
//}
return config
}, error => {
Promise.reject(error)
})
// 3.響應攔截器
service.interceptors.response.use(response => {
//接收到響應數(shù)據(jù)并成功后的一些共有的處理,關閉loading等
return response
}, error => {
/***** 接收到異常響應的處理開始 *****/
if (error && error.response) {
// 1.公共錯誤處理
// 2.根據(jù)響應碼具體處理
switch (error.response.status) {
case 400:
error.message = '錯誤請求'
break;
case 401:
error.message = '未授權,請重新登錄'
break;
case 403:
error.message = '拒絕訪問'
break;
case 404:
error.message = '請求錯誤,未找到該資源'
window.location.href = "/NotFound"
break;
case 405:
error.message = '請求方法未允許'
break;
case 408:
error.message = '請求超時'
break;
case 500:
error.message = '服務器端出錯'
break;
case 501:
error.message = '網(wǎng)絡未實現(xiàn)'
break;
case 502:
error.message = '網(wǎng)絡錯誤'
break;
case 503:
error.message = '服務不可用'
break;
case 504:
error.message = '網(wǎng)絡超時'
break;
case 505:
error.message = 'http版本不支持該請求'
break;
default:
error.message = `連接錯誤${error.response.status}`
}
} else {
// 超時處理
if (JSON.stringify(error).includes('timeout')) {
Message.error('服務器響應超時,請刷新當前頁')
}
error.message = '連接服務器失敗'
}
Message.error(error.message)
/***** 處理結束 *****/
//如果不需要錯誤處理,以上的處理過程都可省略
return Promise.resolve(error.response)
})
//4.導入文件
export default service四、封裝請求-http.js
/**** http.js ****/
// 導入封裝好的axios實例
import request from './request'
const http ={
/**
* methods: 請求
* @param url 請求地址
* @param params 請求參數(shù)
*/
get(url,params){
const config = {
method: 'get',
url:url
}
if(params) config.params = params
return request(config)
},
post(url,params){
const config = {
method: 'post',
url:url
}
if(params) config.data = params
return request(config)
},
put(url,params){
const config = {
method: 'put',
url:url
}
if(params) config.params = params
return request(config)
},
delete(url,params){
const config = {
method: 'delete',
url:url
}
if(params) config.params = params
return request(config)
}
}
//導出
export default http五、正式封裝API用于發(fā)送請求-api.js
import request from "@/utils/request.js";
import qs from "qs";
const baseUrl = '/api/jwt/auth'
//登錄
export function authCodeLogin(params) {
return request({
url: baseUrl + "/authCodeLogin/" + params.code,
method: "get",
});
}
//退出
export function authLogout(params) {
return request({
url: baseUrl + "/logout",
method: "get",
});
}
//獲取用戶數(shù)據(jù)
export function getUserInfo(params) {
return request({
url: baseUrl + "/getUserInfo",
method: "get",
params:qs.stringfy(params)
});
}
//其實,也不一定就是params,也可以是 query 還有 data 的呀!
//params是添加到url的請求字符串中的,用于get請求。會將參數(shù)加到 url后面。所以,傳遞的都是字符串。無法傳遞參數(shù)中含有json格式的數(shù)據(jù)
//而data是添加到請求體(body)中的, 用于post請求。添加到請求體(body)中,json 格式也是可以的。
六、如何在vue文件中調(diào)用
用到哪個api 就調(diào)用哪個接口
import { authCodeLogin } from '@/api/api.js'
getModellogin(code){
let params = {
code: code,
}
authCodeLogin(params).then(res=>{
if (res.code === 200) {
localStorage.clear()
// 菜單
this.$store.dispatch('saveMenu', [])
// this.getFloorMenu()
// this.getmenu()
this.$router.push('/')
}else{
console.log('error');
}
})
},到此這篇關于Vue二次封裝axios流程詳解的文章就介紹到這了,更多相關Vue封裝axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue使用Multiavatarjs生成自定義隨機頭像的案例
這篇文章給大家介紹了Vue項目中使用Multiavatarjs生成自定義隨機頭像的案例,文中通過代碼示例介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下2023-10-10
vue require.context全局注冊組件的具體實現(xiàn)
本文主要介紹了vue require.context全局注冊組件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-05-05
Vue 實現(xiàn)列表動態(tài)添加和刪除的兩種方法小結
今天小編就為大家分享一篇Vue 實現(xiàn)列表動態(tài)添加和刪除的兩種方法小結,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09

