vue3+vite+axios?配置連接后端調用接口的實現方法
更新時間:2022年12月08日 08:24:36 作者:專心致志的程序員!
這篇文章主要介紹了vue3+vite+axios?配置連接后端調用接口的實現方法,在vite.config.ts文件中添加配置,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
在vite.config.ts文件中添加以下配置
export default defineConfig({
plugins: [vue()],
optimizeDeps: {
include: ['axios'],
},
build: {
target: 'modules',
outDir: 'dist',
assetsDir: 'assets',
minify: 'terser' // 混淆器
},
server: {
cors: true,
open: true,
proxy: {
'/api': {
target: 'http://xxx.xxx.xxx', //代理接口
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})在本地項目中新建一個文件夾api文件夾中編寫以下文件
1.配置axios(axios.js)
import axios from "axios"
const instance = axios.create({
baseURL: "/api",
timeout: 5000,
});
// 添加請求攔截器
instance.interceptors.request.use(
(config) => {
// 在發(fā)送請求之前做些什么
config.headers["Content-type"] = "application/json";
return config;
},
(error) => {
// 對請求錯誤做些什么
return Promise.reject(error);
}
);
// 添加響應攔截器
instance.interceptors.response.use(
(response) => {
// 對響應數據做點什么
// 隱藏加載圖
// 獲取code
const res = response.data;
// 返回成功
if (res == 200) {
return res;
}
// token 異常
if (res === 508 || res === 512 || res === 514) {
// 登出 清除token緩存
}
return response;
},
(error) => {
// 對響應錯誤做點什么
return Promise.reject(error);
}
);
export default instance;2.配置請求(request.js)
import instance from "./axios"
const axios = ({
method,
url,
data,
config
}) => {
method = method.toLowerCase();
if (method == 'post') {
return instance.post(url, data, {...config})
} else if (method == 'get') {
return instance.get(url, {
params: data,
...config
})
} else if (method == 'delete') {
return instance.delete(url, {
params: data,
...config
}, )
} else if (method == 'put') {
return instance.put(url, data,{...config})
} else {
console.error('未知的method' + method)
return false
}
}
export default axios3.配置端口
編寫具體的請求,建議按照項目具體情況分文件編寫
import axios from "./request"
//請求示例
//get
export const mokeGet = (data) => {
return axios({
url: "/getTest",
method: "get",
data,
config: {
headers: {
'Request-Type': 'wechat'
},
timeout: 3000
}
})
}
post
export const mokePost = (data) => {
return axios({
url: "/postTest",
method: "post",
data,
config: {
headers: {
'Request-Type': 'wechat'
},
timeout: 3000
}
})
}到此這篇關于vue3+vite+axios 配置連接后端調用接口的文章就介紹到這了,更多相關vue3+vite+axios內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue項目從webpack3.x升級webpack4不完全指南
前段時間,泡面將自己的一個Vue-cli構建的前端框架從webpack3.x升級到了4.x版本,現在才拉出來記錄一下,已備忘之用,也和大家分享一下,需要的朋友可以參考下2019-04-04
Vue 報錯Error: No PostCSS Config foun
這篇文章主要介紹了Vue 報錯Error: No PostCSS Config found問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
vue對storejs獲取的數據進行處理時遇到的幾種問題小結
這篇文章主要介紹了vue對storejs獲取的數據進行處理時遇到的幾種問題小結,需要的朋友可以參考下2018-03-03

