温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue axios 简单封装以及思考

发布时间:2020-09-14 22:34:20 来源:脚本之家 阅读:128 作者:huangenai 栏目:web开发

axios 简介

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

--------------------------------------------------------------------------------
•从浏览器中创建 XMLHttpRequest
•从 node.js 发出 http 请求
•支持 Promise API
•拦截请求和响应
•转换请求和响应数据
•取消请求
•自动转换JSON数据
•客户端支持防止 CSRF/XSRF

先安装 axios

npm install axios

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

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

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

"use strict";
import axios from "axios";
import qs from "qs";
//添加请求拦截器
axios.interceptors.request.use(
 config => {
  return config;
 },
 error => {
  return Promise.reject(error);
 }
);
//添加响应拦截器
axios.interceptors.response.use(
 response => {
  return response;
 },
 error => {
  return Promise.resolve(error.response);
 }
);
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: "网络异常"
   });
  }
 });
}
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: "网络异常"
   });
  }
 });
}

个人觉得这两种方案各有优劣,实际应用中还是应该根据个人业务需求 业务情况而定。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI