基于Spring Boot+Vue的博客系统 05——封装axios

废弃说明:
这个专栏的文章本意是记录笔者第一次搭建博客的过程,文章里里有很多地方的写法都不太恰当,现在已经废弃,关于SpringBoot + Vue 博客系列,笔者重新写了这个系列的文章,不敢说写的好,但是至少思路更加清晰,还在看SpringBoot + Vue 博客系列文章的朋友可以移步:https://blog.csdn.net/li3455277925/category_10341110.html,文章中有错误的地方或者大家有什么意见或建议都可以评论或者私信交流。

0. 使用axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
Axios官网:http://www.axios-js.com/

  • 使用npm install axios进行安装
  • 新建/src/request/http.js,在文件中导入axios,并新建一个实例,设置过期时间以及请求头信息
import axios from 'axios'

// 设置请求超时时间,并创建axios实例
var instance = axios.create({ timeout: 1000 * 12 });
// 设置post请求的请求头
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
instance.defaults.withCredentials = true;

export default instance;
1. 设置400和500界面
  • 新建/src/components/page/error404.vue/src/components/page/error500.vue,分别来展示找不到资源和服务器故障页面
  • error404.vue
<template>
  <b-container class="main">
    <b-img fluid src="/static/images/error/404.png"></b-img>
    <h3>你所访问的页面不存在!</h3>
    <h5>资源不存在或者没有访问权限,点击<b-link to="/">这里</b-link>返回首页</h5>
  </b-container>
</template>
<script>
export default {
  name: "error404"
};
</script>
<style scoped>
.main {
  text-align: center;
  margin-top: 10px;
  padding: 0 20%;
  background-color: #fff;
  border-radius: 5px;
  min-height: 100%;
}
</style>
  • error500.vue
<template>
  <b-container class="main">
    <b-img fluid src="/static/images/error/500.png"></b-img>
    <h3>服务器冒烟了!</h3>
    <h5>你所访问的功能尚在维护或者服务器出现未知错误,点击<b-link to="/">这里</b-link>返回首页</h5>
  </b-container>
</template>
<script>
export default {
  name: "error404"
};
</script>
<style scoped>
.main {
  text-align: center;
  margin-top: 10px;
  padding: 0 20%;
  background-color: #fff;
  border-radius: 5px;
  min-height: 100%;
}
</style>
  • 在路由中注册两个页面,注意这里error404匹配所有路由,并且写在最下面,这样当在地址栏输入无效地址时就跳转到error404界面
import Vue from 'vue'
import Router from 'vue-router'
import mainPage from "@/components/page/mainPage"
import articleDetails from "@/components/page/articleDetails"
import error404 from "@/components/page/error404"
import error500 from "@/components/page/error500"

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'mainPage',
      component: mainPage
    },
    {
      path: '/articleDetails',
      name: "articleDetails",
      component: articleDetails
    },
    {
      path: '/error500',
      name: "error500",
      component: error500
    },
    {
      path: '/*',
      name: "error404",
      component: error404
    }
  ]
})
  • 页面效果:
    页面效果
2. 添加请求拦截

这里主要处理请求超时、服务器错误、资源无法访问的错误

import axios from 'axios'
import router from '@/router/index';

// 设置请求超时时间,并创建axios实例
var instance = axios.create({ timeout: 1000 * 12 });
// 设置post请求的请求头
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
instance.defaults.withCredentials = true;

// 响应拦截
instance.interceptors.response.use(
  response => {
    // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据     
    // 否则的话抛出错误
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    // 请求超时,或者其他网络原因
    if (error.message == 'Network Error' || error.message.includes('timeout')) {
      router.push('/error500');
      return Promise.reject(error);
    }
    // 此处用了es6的解构赋值,相当于:const response = error.response;
    const { response } = error;
    errorHandle(response.status, response.data.message);
    return Promise.reject(response);
  }
);

/** 
 * 请求失败后的错误统一处理 
 * @param {Number} status 请求失败的状态码
 */
const errorHandle = (status, other) => {
  // 状态码判断
  switch (status) {
    // 404请求不存在
    case 404:
      router.push("/error404");
      break;
    case 500:
      router.push("/error500");
      break;
    default:
      console.log(other);
  }
}

export default instance;
3.封装api
  • 新建/src/request/api/url.js存放请求的URL
const baseUrl = "http://localhost:8886/";

const getArticlesUrl = baseUrl + 'getArticles';

export default {
  getArticlesUrl
};
  • 新建/src/request/api/article,用于存放所有关于文章(article)的请求
// 导入axios实例
import axios from "@/request/http"
// 导入所有url
import url from '@/request/api/url'

export default {
  getArticles(callback) {
    axios
      .get(url.getArticlesUrl)
      .then(callback)
      .catch(err => {
        console.log('getArticles Error');
      });
  }
}
  • 新建/src/request/api/index.js,用于导出所有请求
/** 
 * api接口的统一出口
 */
// 文章模块接口
import article from '@/request/api/article';

// 导出接口
export default {
  article
}
  • 修改main.js,将所有请求挂在Vue的原型链上
    挂在原型链上

参考博客:vue中Axios的封装和API接口的管理

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值