需要安装 axios,qs
yarn add axios npm i axios cnpm i axios
yarn add qs npm i qs cnpm i qs
在src/API/axios.ts
import axios from 'axios'; import qs from "qs"; axios.defaults.baseURL = "/api"; // 请求地址统一配置到vite.config.ts中代理 axios.defaults.headers.post["Content-Type"] = "application/json"; // axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest"; axios.defaults.timeout = 20000; //设置请求超时时间 // 请求拦截器 axios.interceptors.request.use( (config) => { // 可以在这里添加请求头、认证token等 // 例如:config.headers['Authorization'] = 'Bearer ' + token; return config; }, (error: any) => { // 请求错误处理 return Promise.reject(error); } ); // 响应拦截器 axios.interceptors.response.use( (response) => { return response; }, (error: any) => { // 响应错误处理 return Promise.reject(error); } ); function checkStatus(response: any) { return new Promise((resolve, reject) => { if (response && (response.status === 200 || response.status === 304 || response.status === 400)) { try { resolve(response.data); } catch (e) { //抛出异常 console.log(e) } } else { try { console.log("网络异常,请检查网络连接是否正常!") } catch (e) { //抛出异常 console.log(e) } } }); } export default { post(url: any, params: any) { return axios({ method: "post", url, data: params }).then(response => { return checkStatus(response); }); }, get(url: any, params?: any) { params = qs.stringify(params); return axios({ method: "get", url, params }).then(response => { return checkStatus(response); }); } };
vite.config.ts
特别注意: target: 后面在加上/api,否则会报404
export default defineConfig({ server: { proxy: { '/api': { target: 'http://xxxxxxxxx/api', // 目标服务器地址 changeOrigin: true, // 是否改变源地址 rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径 // 可以配置更多选项,如 logLevel, timeout 等 }, }, }, })
标签:qs,axios,return,ts,any,params,vue3,response From: https://www.cnblogs.com/tlfe/p/18435542