从零开始搭建vue项目 请求拦截器 响应拦截器

1.安装vue cli,基于webpack模版

 基于webpack模版初始化一个名称为admin的项目vue init webpack admin-vue


1 npm install -g vue-cli
2 vue init webpack my-project
3 cd my-project
4 npm install
5 npm run dev 


文档数结构

 1 .
 2 ├── build webpack打包相关的配置文件目录
 3 ├── config webpack打包相关的配置文件目录
 4 ├── node_modules第三方依赖包 千万不要动它
 5 ├── src项目源码
 6 │   ├── assets存储资源,例如 css、 img、 fonts
 7 │   ├── common存储一些公共的业务组件
 8 │   ├── components存储所有组件
 9 │   ├── router路由
10         └──  index.js路由配置文件
11 │   ├── App.vue  单页面应用程序的根组件
12 │   └── main.js  开机键,负责把根组件替换到根节点
13 ├── static  可以放一些静态资源
14 │   └── .gitkeep
15 ├── .babelrc  es6转es5配置文件,给 babel 编译器用的
16 ├── .editorconfig 
17 ├── .eslintignore  eslint配置文件
18 ├── .eslintrc.js  eslint配置文件
19 ├── .gitignore  git忽略上传文件
20 ├── index.html  单页面引用程序的单页
21 ├── package.json 项目依赖项等信息
22 ├── package-lock.json
23 ├── .postcssrc.js  postcss类似于 less、sass 预处理器
24 └── README.md

 

2.导入ElementUI

1 安装 依赖 npm install element-ui
2 复制表单源码
3 安装axios   npm i axios

 

3.封装axios扩展为vue插件


 1 import axios from 'axios'
 2 import { getToken } from '@/assets/js/auth'
 3 const http = axios.create({
 4   baseURL: 'http://localhost:8888/api/private/v1'
 5 })
 6  7 // vue插件
 8 // https://cn.vuejs.org/v2/guide/plugins.html#开发插件
 9 const httpPlugin = {}
10 httpPlugin.install = function (Vue, options) {
11   // 4. 添加实例方法
12   Vue.prototype.$http = http
13 }
14 export default httpPlugin
15 // 5 在main.js加载
16 // vue.use(httpPlugin)
17
  • 在全局组件中调用$http来发起请求例如

 

请求拦截器

 1 // https://github.com/axios/axios
 2 // axios 配置请求拦截器
 3 http.interceptors.request.use(function (config) {
 4   // Do something before request is sent
 5   if (config.url != '/login') {
 6     config.headers['Authorization'] = getToken()
 7   }
 8   return config;
 9 }, function (error) {
10   // Do something with request error
11   return Promise.reject(error);
12 });

响应拦截器

// axios 配置响应拦截器
// Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data
  const { meta } = response.data
  if (meta.status === 403) {
    window.alert('你没有权限执行该操作!')
  } else if (meta.status === 401) {
    // 401 token 失效 跳转到登录组件
    router.push({
      name: ' login',
      query: {
        redirect: window.location.hash
      }
    })
  }
  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});
posted @ 2018-06-24 21:06  甜土豆  阅读(918)  评论(0编辑  收藏  举报