網(wǎng)站建設(shè) 010東莞網(wǎng)絡(luò)營(yíng)銷優(yōu)化
目錄
- 一、前言
- 二、封裝axios
- 三、 解決跨域
- 四、調(diào)用接口
- 五、運(yùn)行結(jié)果
一、前言
前端請(qǐng)求后端數(shù)據(jù)時(shí),會(huì)用到axios,但是如果不將axios封裝好,會(huì)導(dǎo)致代碼冗余
二次封裝的好處如下:
- 求頭能統(tǒng)一處理
- 便于接口的統(tǒng)一管理
- 解決回調(diào)地獄
- 配置攔截器,給不同的實(shí)例配置不同的攔截器,支持以對(duì)象形式接受多個(gè)攔截器配置
因此,在這里記錄一下axios的封裝過(guò)程。
二、封裝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, // 請(qǐng)求超時(shí)時(shí)間headers:{'Content-Type': 'application/json;charset=UTF-8',}
});// 請(qǐng)求攔截器
instance.interceptors.request.use(config => {// 在發(fā)送請(qǐng)求之前做些什么,例如添加token// config.headers['Authorization'] = 'Bearer your-token';return config;},error => {// 對(duì)請(qǐng)求錯(cuò)誤做些什么return Promise.reject(error);}
);// 響應(yīng)攔截器
instance.interceptors.response.use(response => {// 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么return response;},error => {// 對(duì)響應(yīng)錯(cuò)誤做點(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
文件的目的是為了方便管理接口,你可以把所有接口卸載這里,這樣就會(huì)在后面調(diào)用時(shí)更加簡(jiǎn)潔
三、 解決跨域
在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ǔ)路徑//orbaseURL: '/api/', // API 基礎(chǔ)路徑
四、調(diào)用接口
沒(méi)有使用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é)果
可以看到控制臺(tái)返回的亂碼數(shù)據(jù),表示我們請(qǐng)求后臺(tái)成功了