vue中axios的封装

先安装 axioshtml

npm install axios

axios的详细介绍以及用法 就很少说了请 移步 github ➡️  https://github.com/axios/axiosvue

 

下面是简单的封装一个 http.js, 在此说明  checkStatus 这个方法呢 是不必定须要的 ,根据我的的项目需求吧,也能够直接返回response,交给后面另行处理也行。ios

或者根据后端返回的状态,在里面进行处理 也行。git

"use strict";github

import axios from "axios";
 npm

//添加请求拦截器
axios.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);json

//添加响应拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    return Promise.resolve(error.response);
  }
);axios

axios.defaults.baseURL = "https://www.xxxx/api";
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.timeout = 10000;后端

function checkStatus(response) {
  return new Promise((resolve, reject) => {
    if (
      response &&
      (response.status === 200 ||
        response.status === 304 ||
        response.status === 400)
    ) {
      resolve(response.data);
    } else {
      reject({
        state: "0",
        message: "网络异常"
      });
    }
  });
}api

export default {
  post(url, params) {
    return axios({
      method: "post",
      url,
      data: params
    }).then(response => {
      return checkStatus(response);
    });
  },
  get(url, params) {
    params = qs.stringify(params);
    return axios({
      method: "get",
      url,
      params
    }).then(response => {
      return checkStatus(response);
    });
  }
};

在vue 项目中,main.js这个文件

import http from "./utils/http";


Vue.prototype.$http = http;

使用 helloworld.vue

复制代码

...
methods: {
    async TestPost() {
      try {
        const res = await this.$http.post("/message/socketid", {
          account: "huangenai"
        });
        console.log(res);
      } catch (error) {
        console.log(error);
      }
    },
    async TestGet() {
      this.$http
        .get("/price")
        .then(res => {
          console.log(res);
        })
        .catch(error => {
          alert(error);
        });
    }
}
....

复制代码

 

在main.js中将http.js import 进来 并暴露到全局使用,在任何vue 页面中 就再也不须要 import http.js了,而直接经过 this.$http.post this.$http.get 来使用,在checkStatus中统一异步返回,顺即可以处理错误的状况。

 

我的思考:

checkStatus方法 返回了一个 Promise

链式结构的话看上面那个get的方法,this.$http.get(...).then(...).catch(...),若是then 里面又来一个 http请求 会一层包住一层。

若是使用了语法糖 async  await  ,虽然 看起来好像是简单了 不用 一层包住一层 层层嵌套,但是你必需要用到 try catch,若是出现异常 则直接到catch,不会再执行下面到方法。若是再实际业务中,就算出现了某一个http请求失败到状况,不影响下面的逻辑要继续跑下去呢,这个就不适用了。链式结构也是 若是catch到异常 也不会执行then 里面到方法了。

因此,是否把返回的Promise,所有都返回的是 resolve,那么 就不会说出现直接到了 catch 里面不执行如下的业务了逻辑了呢。并且若是使用了语法糖 await 代码看起来更加简洁 也不须要 try catch了, 这样的话 reject是否是就不须要用到了呢。

复制代码

function checkStatus(response) {
  return new Promise(resolve => {
    if (
      response &&
      (response.status === 200 ||
        response.status === 304 ||
        response.status === 400)
    ) {
      resolve(response.data);
    } else {
      resolve({
        state: "0",
        message: "网络异常"
      });
    }
  });
}

复制代码

我的以为这两种方案各有优劣,实际应用中仍是应该根据我的业务需求 业务状况而定。

 

引自 https://www.cnblogs.com/huangenai/p/9760039.html

相关文章
相关标签/搜索