vue3 axios请求封装
来源:原创
时间:2023-06-29
作者:脚本小站
分类:JS/JQuery
文件路径:src/utils/requests.js
import axios from 'axios' import querystring from 'querystring' const errorHandle = (status, info) => { switch(status){ case 400: console.log("语义有误"); break; case 401: console.log("服务器认证失败"); break; case 403: console.log("服务器拒绝访问"); break; case 404: console.log("地址错误"); break; case 500: console.log("服务器遇到意外"); break; case 502: console.log("服务器无响应"); break; default: console.log(info); break; } } const instance = axios.create({ // 网络请求公共配置 timeout: 5000 }) // 请求拦截器 // 发送数据之前 instance.interceptors.request.use( // 成功配置 config => { // 在拦截器中处理数据,如:将json数据转换为 name=John&age=25&email=john%40example.com 这样的数据 if(config.method === "post"){ config.data = querystring.stringify(config.data) } return config; }, // 失败配置 error => { return Promise.reject(error) } ) // 响应拦截器 instance.interceptors.response.use( response => { return response.status === 200 ? Promise.resolve(response) : Promise.reject(response) }, error => { const { response } = error; // 处理错误消息 errorHandle(response.status, response.info) } ) export default instance;
src/api/path.js
import axios from "../utils/requests"; import path from "./path"; const api = { getChengpin (){ return axios.get(path.chengpin) }, chengpinInfo(){ return axios.get(path.chengpinInfo) }, FingerUnion(){ return axios.get(path.FingerUnion) } } export default api;
src/api/index.js
const base = { baseUrl: "http://demo.com", chengpin: "/api/blueberrypai/getChengpinDetails.php", chengpinInfo: "/api/blueberrypai/getChengpinInfo.php", FingerUnion: "/api/FingerUnion/list.php", } export default base;
解决跨域问题:vue.config.js
import { fileURLToPath, URL } from 'node:url' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue(), ], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }, // 解决跨域的配置 server: { proxy: { '/api': { target: 'http://demo.com', changeOrigin: true } } } })