vue3+vite+axios?配置連接后端調(diào)用接口的實(shí)現(xiàn)方法
在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/, '')
}
}
}
})在本地項(xiàng)目中新建一個(gè)文件夾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) => {
// 對請求錯(cuò)誤做些什么
return Promise.reject(error);
}
);
// 添加響應(yīng)攔截器
instance.interceptors.response.use(
(response) => {
// 對響應(yīng)數(shù)據(jù)做點(diǎn)什么
// 隱藏加載圖
// 獲取code
const res = response.data;
// 返回成功
if (res == 200) {
return res;
}
// token 異常
if (res === 508 || res === 512 || res === 514) {
// 登出 清除token緩存
}
return response;
},
(error) => {
// 對響應(yīng)錯(cuò)誤做點(diǎn)什么
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.配置端口
編寫具體的請求,建議按照項(xiàng)目具體情況分文件編寫
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
}
})
}到此這篇關(guān)于vue3+vite+axios 配置連接后端調(diào)用接口的文章就介紹到這了,更多相關(guān)vue3+vite+axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue項(xiàng)目從webpack3.x升級webpack4不完全指南
前段時(shí)間,泡面將自己的一個(gè)Vue-cli構(gòu)建的前端框架從webpack3.x升級到了4.x版本,現(xiàn)在才拉出來記錄一下,已備忘之用,也和大家分享一下,需要的朋友可以參考下2019-04-04
Vue 報(bào)錯(cuò)Error: No PostCSS Config foun
這篇文章主要介紹了Vue 報(bào)錯(cuò)Error: No PostCSS Config found問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
vue對storejs獲取的數(shù)據(jù)進(jìn)行處理時(shí)遇到的幾種問題小結(jié)
這篇文章主要介紹了vue對storejs獲取的數(shù)據(jù)進(jìn)行處理時(shí)遇到的幾種問題小結(jié),需要的朋友可以參考下2018-03-03
使用vue3+vite導(dǎo)入圖片路徑錯(cuò)亂問題排查及解決
使用vue3+vite開發(fā)的時(shí)候,導(dǎo)入svg圖片時(shí),同一個(gè)文件夾下的文件,其中一個(gè)路徑正常解析,另一個(gè)不行,更改文件名之后,該圖片文件就可以正常解析了,本文給大家介紹了使用vue3+vite導(dǎo)入圖片路徑錯(cuò)亂問題排查及解決,需要的朋友可以參考下2024-03-03

