Vue实现数据请求拦截

本文实例为大家分享了vue数据请求拦截的具体代码,供大家参考,具体内容如下

在src文件夹下创建utils文件夹

同时在文件夹下创建request.js和auth.js文件

request.js为请求拦截、请求数据封装主入口
auth.js为设置token和删除token及判断用户是否登录封装主入口

auth.js (封装token)

export function isLogin() {
  if (localStorage.getItem('token')) {
   return true;
  } else {
   return false;
  }
 }
 export function getToken() {
  return localStorage.getItem('token');
 }
 export function setToken(token) {
  localStorage.setItem('token', token);
 }

 export function removeToken() {
  localStorage.removeItem('token');
 }

下载axios(命令: npm install axios --save-dev)、同时引入axios、getToken

import axios from 'axios';
import { getToken } from './auth';

创建实例:传两个参数(timeout(超时时间)、baseUrl(服务器路径))

const instance = axios.create({
   timeout: 5000,
   baseURL: 'https://xxxxxxxxx/xxxx/',
 });

请求拦截

// 请求拦截
 instance.interceptors.request.use(
  function(config) {
   // eslint-disable-next-line prettier/prettier
   config.headers.authorization = 'Bearer ' + getToken();
   return config;
  },
  function(error) {
   // Do something with request error
   return Promise.reject(error);
  }
 );

 instance.interceptors.response.use(
  response => {
   return response;
  },
  error => {
   if (error.response.status == 401) {
    window.location.href = '/#/login';
   }
   if (error.response.status == 404) {
    window.location.href = '/404.html';
   }
   return Promise.reject(error.response.data);
  }
 );

请求封装

 /**
  * 获取数据 get请求
  * @param {*} url
  * @param {*} config
  */
 export const get = (url, config) => instance.get(url, config);

 /**
  * post请求
  * @param {*} url
  * @param {*} data
  * @param {*} config
  */
 export const post = (url, data) => instance.post(url, data);
 /**
  * put
  * @param {*} url
  * @param {*} data
  * @param {*} config
  */
 export const put = (url, data, config) => instance.put(url, data, config);

 /**
  * delete
  * @param {*} url
  * @param {*} config
  */
 export const remove = (url, config) => instance.delete(url, config);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • vuejs前后端数据交互之从后端请求数据的实例

    本文将向大家介绍一种用vue-resource从后端请求数据的方法. 比如说从后端请求一张表过来, (1)首先,在data中return一个msg:[]数组来接收表的数据: (2)在方法中定义一个请求函数,比如我们这里函数名定义为showDetails: methods:{ showDetails:function(){ this.$http.get(baseURL+"api/条件").then(function(res){ this.msg = res.body; }); } } 这

  • vue2实现数据请求显示loading图

    一般项目中,有时候会要求,你在数据请求的时候显示一张gif图片,然后数据加载完后,消失.这个,一般只需要在封装的axios中写入js事件即可.当然,我们首先需要在app.vue中,加入此图片.如下: <template> <div id="app"> <loading v-show="fetchLoading"></loading> <router-view></router-view> <

  • 详解在vue-cli项目中使用mockjs(请求数据删除数据)

    在我们的生产实际中,后端的接口往往是较晚才会出来,于是我们的前端的许多开发都要等到接口给我们才能进行,这样对于我们前端来说显得十分的被动,于是有没有可以制造假数据来模拟后端接口呢,答案是肯定的.于是今天我们来介绍一款非常强大的插件Mock.js,可以非常方便的模拟后端的数据,也可以轻松的实现增删改查这些操作,在后台数据完成之后,你所做的只是去掉mockjs:停止拦截真实的ajax,仅此而已. 搭建一个vue项目 # 全局安装 vue-cli $ npm install --global vue-

  • vue如何从接口请求数据

    这两天学习了vue如何从接口请求数据,所以,今天添加一点小笔记. <!doctype html> <html> <head> <meta charset="UTF-8"> <title>获取图片列表</title> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,m

  • vue.js实现请求数据的方法示例

    vue2.0示例代码如下: var vm = new Vue({ el:"#list", data:{ gridData: "", }, mounted: function() { this.$nextTick(function () { this.$http.jsonp('http://***.com').then(function(res) { console.log(res.data) this.gridData = res.data; }) }) }, })

  • Vue+axios 实现http拦截及路由拦截实例

    现如今,每个前端对于Vue都不会陌生,Vue框架是如今最流行的前端框架之一,其势头直追react.最近我用vue做了一个项目,下面便是我从中取得的一点收获. 基于现在用vue+webpack搭建项目的文档已经有很多了,我就不再累述了. 技术栈 vue2.0 vue-router axios 拦截器 首先我们要明白设置拦截器的目的是什么,当我们需要统一处理http请求和响应时我们通过设置拦截器处理方便很多. 这个项目我引入了element ui框架,所以我是结合element中loading和me

  • vue 请求后台数据的实例代码

    需要引用vue-resource 安装请参考https://github.com/pagekit/vue-resource官方文档 在入口函数中加入 import VueResource from 'vue-resource' Vue.use(VueResource); 在package.json文件中加入 "dependencies": { "vue": "^2.2.6", "vue-resource":"^1.2

  • vue路由拦截及页面跳转的设置方法

    路由设置:router/index.js export default new Router({ routes: [ { path: '/selfcenter', name: 'selfcenter', meta: { requireAuth: true // 配置此条,进入页面前判断是否需要登陆 }, component: selfcenter } ] }) main.js: /* eslint-disable no-new */ router.beforeEach((to, from, ne

  • Vue2学习笔记之请求数据交互vue-resource

    基本语法 必须引入一个库:vue-resource github地址 // 基于全局Vue对象使用http Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback); Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback); // 在一个Vue实例内使用$http this.$http.get('/so

  • Vue2.0 axios前后端登陆拦截器(实例讲解)

    vue更新到2.0之后,作者就宣告不再对vue-resource更新,而是推荐使用axios.前段时间第一次在项目里用到vue,关于登陆问题,这里写一下心得. 首先后端: import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.lovnx.gateway.po.User; import javax.servlet.http.HttpServletRequest; import jav

随机推荐