vue3简单封装axios
安装依赖
npm install axios --save npm install qs --save
在项目目录中创建axios.js
网络异常,图片无法展示
|
import axios from "axios"; import qs from "qs"; // axios.defaults.baseURL = '' //正式 axios.defaults.baseURL = 'http://127.0.0.1:8080' //测试地址,按需更改 //post请求头 axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"; //允许跨域携带cookie信息 axios.defaults.withCredentials = true; //设置超时 axios.defaults.timeout = 15000; axios.interceptors.request.use( config => { return config; }, error => { return Promise.reject(error); } ); axios.interceptors.response.use( response => { if (response.status === 200) { return Promise.resolve(response); } else { return Promise.reject(response); } }, error => { window.alert(JSON.stringify(error), '请求异常', { confirmButtonText: '确定', callback: (action) => { console.log(action) } }); } ); export default { /** * @param {String} url * @param {Object} data * @returns Promise */ post(url, data) { return new Promise((resolve, reject) => { axios({ method: 'post', url, data: qs.stringify(data), }) .then(res => { resolve(res.data) }) .catch(err => { reject(err) }); }) }, get(url, data) { return new Promise((resolve, reject) => { axios({ method: 'get', url, params: data, }) .then(res => { resolve(res.data) }) .catch(err => { reject(err) }) }) } };
在main.js中
import axios from './util/axios'; app.config.globalProperties.$axios = axios;
封装api使用
import axios from "./axios"; let {get, post } = axios //get举例 export const getCaptcha = data => get("/xxxx",data) //POST export const postModel = data => post("/xxxx",data)
在组建中调用api
import {getCaptcha, postModel} from "@/request/api" // 放在函数,或者生命周期里 postModel({ //data }).then(res => { console.log(res) })