npm i axios
目录
request.ts (直接复制可用)
import axios from "axios"; import { showMessage } from "./status"; // 引入状态码文件 import { ElMessage } from "element-plus"; // 引入el 提示框,这个项目里用什么组件库这里引什么 // 设置接口超时时间 axios.defaults.timeout = 60000; axios.defaults.baseURL = "/api" || ""; // 自定义接口地址 const token = () => { if (sessionStorage.getItem("token")) { return sessionStorage.getItem("token"); } else { return sessionStorage.getItem("token"); } }; //请求拦截 axios.interceptors.request.use( (config) => { // 配置请求头 config.headers["Content-Type"] = "application/json;charset=UTF-8"; config.headers["token"] = token(); return config; }, (error) => { return Promise.reject(error); } ); // 响应拦截 axios.interceptors.response.use( (response) => { return response; }, (error) => { const { response } = error; if (response) { // 请求已发出,但是不在2xx的范围 showMessage(response.status); // 传入响应码,匹配响应码对应信息 return Promise.reject(response.data); } else { ElMessage.warning("网络连接异常,请稍后再试!"); } } ); // 封装 请求并导出 export function request(data: any) { return new Promise((resolve, reject) => { const promise = axios(data); //处理返回 promise .then((res: any) => { resolve(res.data); }) .catch((err: any) => { reject(err.data); }); }); }
status.ts (直接复制可用)
export const showMessage = (status: number | string): string => { let message: string = ""; switch (status) { case 400: message = "请求错误(400)"; break; case 401: message = "未授权,请重新登录(401)"; break; case 403: message = "拒绝访问(403)"; break; case 404: message = "请求出错(404)"; break; case 408: message = "请求超时(408)"; break; case 500: message = "服务器错误(500)"; break; case 501: message = "服务未实现(501)"; break; case 502: message = "网络错误(502)"; break; case 503: message = "服务不可用(503)"; break; case 504: message = "网络超时(504)"; break; case 505: message = "HTTP版本不受支持(505)"; break; default: message = `连接出错(${status})!`; } return `${message},请检查网络或联系管理员!`; };
不要忘了配置代理
在 vite.config.ts 里
export default defineConfig({ server: { host: "192.168.0.0", port: 8080, https: false, // 跨域的写法 proxy: { "/api": { target: "http://192.168.2.12:8080", // 实际请求地址 changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ""), }, }, }, });
如何应用
import { request } from "../utils/request"; export function login(data: any) { return request({ url: "/login", method: "post", data, }); }export function list(params: any) { return request({ url: "/list", method: "get", params, }); }
const submitForm = () => { login({username: "", password: ""}).then((res: any) => { console.log(res, "请求成功") }) }
标签:case,axios,return,request,ts,break,message,vite From: https://www.cnblogs.com/wqddmg/p/17362652.html