diff --git a/web/src/api/index.js b/web/src/api/index.js new file mode 100644 index 0000000..4e91c46 --- /dev/null +++ b/web/src/api/index.js @@ -0,0 +1,11 @@ +import http from '../utils/http' + +export default { + login(username, password) { + return http.post('/user/login', { username, password }) + }, + + getInfo() { + return http.get('/user/info') + } +} \ No newline at end of file diff --git a/web/src/utils/http.js b/web/src/utils/http.js new file mode 100644 index 0000000..d460686 --- /dev/null +++ b/web/src/utils/http.js @@ -0,0 +1,62 @@ +// src/utils/http.js +import axios from '../config/service' // 基础配置 + +/** + * 高级请求封装 + */ +const http = { + /** + * GET 请求 + * @param {string} url + * @param {object} params + * @param {object} config + */ + get(url, params = {}, config = {}) { + return axios.get(url, { params, ...config }) + }, + + /** + * POST 请求 + * @param {string} url + * @param {object} data + * @param {object} config + */ + post(url, data = {}, config = {}) { + return axios.post(url, data, config) + }, + + /** + * PUT 请求 + * @param {string} url + * @param {object} data + * @param {object} config + */ + put(url, data = {}, config = {}) { + return axios.put(url, data, config) + }, + + /** + * DELETE 请求 + * @param {string} url + * @param {object} params + * @param {object} config + */ + delete(url, params = {}, config = {}) { + return axios.delete(url, { params, ...config }) + }, + + /** + * 文件上传 + * @param {string} url + * @param {FormData} formData + * @param {object} config + */ + upload(url, formData, config = {}) { + return axios.post(url, formData, { + headers: { 'Content-Type': 'multipart/form-data' }, + ...config + }) + } +} + +export default http \ No newline at end of file diff --git a/web/src/utils/service.js b/web/src/utils/service.js new file mode 100644 index 0000000..1e71d05 --- /dev/null +++ b/web/src/utils/service.js @@ -0,0 +1,33 @@ +import axios from 'axios'; + +// 创建 Axios 实例 +const service = axios.create({ + baseURL: import.meta.env.VITE_API_BASE_URL || '/api', // 从环境变量读取 + timeout: 10000, // 请求超时时间 +}); + +// 请求拦截器 +service.interceptors.request.use( + config => { + // 可在此添加 token 等 + // config.headers['Authorization'] = getToken(); + return config; + }, + error => { + return Promise.reject(error); + } +); + +// 响应拦截器 +service.interceptors.response.use( + response => { + // 可在此统一处理响应数据 + return response.data; + }, + error => { + // 可在此统一处理错误 + return Promise.reject(error); + } +); + +export default service; \ No newline at end of file