common/post.js
import axios from ‘axios‘ // 引入axios import qs from ‘qs‘ // 引入qs axios.defaults.baseURL = ‘/apis‘ //请求地址的域名(此处使用了代理所以直接填/apis // 拦截响应response,进行错误处理 axios.interceptors.response.use(function (response) { // 成功处理 // code处理 response.code = response.data.code switch (response.status) { case 200: break; case 400: response.data.msg = ‘错误请求‘ break; case 401: response.data.msg = ‘未授权,请重新登录‘ break; case 403: response.data.msg = ‘拒绝访问‘ break; case 404: response.data.msg = ‘请求错误,未找到该资源‘ break; case 405: response.data.msg = ‘请求方法未允许‘ break; case 408: response.data.msg = ‘请求超时‘ break; case 500: response.data.msg = ‘服务器端出错‘ break; case 501: response.data.msg = ‘网络未实现‘ break; case 502: response.data.msg = ‘网络错误‘ break; case 503: response.data.msg = ‘服务不可用‘ break; case 504: response.data.msg = ‘网络超时‘ break; case 505: response.data.msg = ‘http版本不支持该请求‘ break; } return response; }, function (error) { return Promise.reject(error); }); async function requestGet(options) { // 这里主要是post方法的封装,get方法同理 options.method = ‘post‘ if (options.config === ‘formData‘) { options.headers = {‘Content-Type‘: ‘multipart/form-data‘} } else { options.data = qs.stringify(options.data) } return new Promise((resolve,reject) => { axios(options).then(res => { // 这里主要根据后来返回的数据作判断,请根据实际情况 if(res.data.code == ‘200‘) { resolve(res.data) } else { reject(res.data) } }).catch(error => { // 显示拦截器对respone处理后的可读错误 console.log(error) }) }) } export default { requestGet }
main.js
import Post from ‘../static/js/post.js‘/*post公共*/ const { requestPost } = Post/*post*/ Vue.prototype.$requestPost = requestPost // post挂载到全局上
页面中:
acceptlist(){ this.$requestGet({ url: this.http+‘/cdk/paperTypeMobile/findList‘, data: {} }).then(res => { console.log(res) this.columns=res.obj }).catch(err=>{ console.log(err) }) }
注:main.js和post.js中要引入axios、qs
原文地址:https://www.cnblogs.com/weilizou/p/10937645.html
时间: 2024-10-08 10:47:54