Vue Promise封装接口get和post

Vue Promise封装接口

因为实际开发的时候要和别人对接口,有时候不仅是和一个java对接口,要和很多人对,这个时候页面在请求数据的时候就比较烦了,如果不对接口做封装的话,后面切换的时候每个页面都要改地址,然后还有就是Promise,我看了我师父的代码。PS:不知道我理解的对不对 改天问下我师父,我觉得我应该对了,下面给出这个配置的全部代码。
在这里插入图片描述

Vue.prototype.$http = http;

Vue.prototype.$post = function(url, data) {
  return new Promise((resolve, reject) => {
    http
      .post(url, data)
      .then((res) => {
        if (res.status == 200) {
          resolve(res.data);
        } else {
          ElementUI.Message.error(res.data.msg);
        }
      })
      .catch((err) => {
        // ElementUI.Message.error('网络错误,请重试!')

        reject(err);
      });
  });
};

这个是源代码。
在这里插入图片描述
上图是在页面中使用的。
promise是处理异步操作的,只会返回resolve和reject,reject是失败的数据,resolve是成功的数据
第一张图就是请求接口的时候如果成功了,就是.then,那么resolve就传后端的数据,如果.catch,就往reject里传错误的信息,然后在调用的时候,因为Promise本身在原型链中有catch和then,分别对应了resolve和reject。
在这里插入图片描述

import Vue from "vue";
import axios from "axios";
import ElementUI from "element-ui";
require("es6-promise").polyfill();

const http = axios.create({
  baseURL: window.BASEPATH,
  headers: {
    "X-Requested-With": "X-Requested-With",
  },
  withCredentials:true,/*允许携带cookie*/
  timeout: process.env.NODE_ENV === "production" ? 100000 : 100000, // 5000
});

// 添加响应拦截器
http.interceptors.response.use( //interceptors 请求拦截的意思  response是响应拦截
  (response) => {
    // 登录失效,跳转登录
    if (response.data.Code === "201") {
      window.location =
        response.data.Data +
        "?returnurl=" +
        encodeURIComponent(encodeURIComponent(window.location));
      return response;
    } else {
      return response;
    }
  },
  (error) => {
    // 对响应错误做点什么
    console.log("response--", error);
    return Promise.reject(error);
  }
);

//封装接口

Vue.prototype.$http = http;

Vue.prototype.$post = function(url, data) {
  return new Promise((resolve, reject) => {
    http
      .post(url, data)
      .then((res) => {
        if (res.status == 200) {
          resolve(res.data);
        } else {
          ElementUI.Message.error(res.data.msg);
        }
      })
      .catch((err) => {
        // ElementUI.Message.error('网络错误,请重试!')
        reject(err);
      });
  });
};

//         reject(err);
//       });
//   });
// };

Vue.prototype.$get = function(url, params = {}) {
  return new Promise((resolve, reject) => {
    http
      .get(url, {
        params,
      })
      .then((res) => {
        if (res.status == 200) {
          resolve(res);
        } else {
          ElementUI.Message.error(res.data.msg);
        }
      })
      .catch((err) => {
        // ElementUI.Message.error('网络错误,请重试!')
        reject(err);
      });
  });
};

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值