小言_互联网的博客

小白搭博客(基于Spring Boot+Vue)05——封装axios

291人阅读  评论(0)

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接口的管理


转载:https://blog.csdn.net/li3455277925/article/details/102488127
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场