vue3+ts封裝axios實(shí)例以及解決跨域問題
一、前言
前端請求后端數(shù)據(jù)時(shí),會用到axios,但是如果不將axios封裝好,會導(dǎo)致代碼冗余
二次封裝的好處如下:
- 求頭能統(tǒng)一處理
- 便于接口的統(tǒng)一管理
- 解決回調(diào)地獄
- 配置攔截器,給不同的實(shí)例配置不同的攔截器,支持以對象形式接受多個(gè)攔截器配置
因此,在這里記錄一下axios的封裝過程。
二、封裝axios
安裝axios
npm install axios
在目錄/src/utils下創(chuàng)建一個(gè)http的文件夾

request.ts文件內(nèi)容如下:
import axios from 'axios';
// 創(chuàng)建 axios 實(shí)例
const instance = axios.create({
baseURL: 'http://127.0.0.1:4008/api/', // API 基礎(chǔ)路徑
timeout: 100000, // 請求超時(shí)時(shí)間
headers:{
'Content-Type': 'application/json;charset=UTF-8',
}
});
// 請求攔截器
instance.interceptors.request.use(
config => {
// 在發(fā)送請求之前做些什么,例如添加token
// config.headers['Authorization'] = 'Bearer your-token';
return config;
},
error => {
// 對請求錯誤做些什么
return Promise.reject(error);
}
);
// 響應(yīng)攔截器
instance.interceptors.response.use(
response => {
// 對響應(yīng)數(shù)據(jù)做點(diǎn)什么
return response;
},
error => {
// 對響應(yīng)錯誤做點(diǎn)什么
return Promise.reject(error);
}
);
export default instance;
api.ts文件如下:
import http from './request'
export const generateVoice = (params:any) => {
return http.request({
method: 'POST',
url: '/generate_voice',
headers: {
'Content-Type': 'application/json'
},
data:JSON.stringify(params)
})
}api.ts文件的目的是為了方便管理接口,你可以把所有接口卸載這里,這樣就會在后面調(diào)用時(shí)更加簡潔
三、 解決跨域
在vite.config.ts文件中添加如下配置
server: {
port: 4008,
host: '0.0.0.0',
proxy: {
"/api": {
target: "http://64.176.215.21:8000/",
changeOrigin: false,
ws: true,
rewrite:(path) => path.replace(/^\/api/, "")
}
},
},注意 配置以上文件,你的接口就需要每次帶上/api前綴
在request.ts文件中,我們已經(jīng)做好了每次帶上/api前綴的代碼
baseURL: 'http://127.0.0.1:4008/api/', // API 基礎(chǔ)路徑 //or baseURL: '/api/', // API 基礎(chǔ)路徑
四、調(diào)用接口
沒有使用api.ts的接口
axios.post('/generate_voice',param)
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});使用api.ts封裝好的接口
import {generateVoice} from '@/utils/http/api';
generateVoice(param)
.then(response => {
console.log("Voice generated successfully:", response.data);
})
.catch(error => {
console.error("Error generating voice:", error);
});五、運(yùn)行結(jié)果
可以看到控制臺返回的亂碼數(shù)據(jù),表示我們請求后臺成功了

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于vue.js中this.$emit的理解使用
本文主要介紹了關(guān)于vue.js中this.$emit的理解使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
VUE + UEditor 單圖片跨域上傳功能的實(shí)現(xiàn)方法
這篇文章主要介紹了VUE + UEditor 單圖片跨域上傳功能的實(shí)現(xiàn)方法,需要的朋友參考下2018-02-02
Vue實(shí)現(xiàn)點(diǎn)擊當(dāng)前行變色
這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)點(diǎn)擊當(dāng)前行變色,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12

