Spring Boot Vue Element入门实战(五)封装axios

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/u013254183/article/details/99292624

本博客属作者原创,未经允许禁止转载,请尊重原创!如有问题请联系QQ509961766

(一)创建axios.js

在src目录下新建axios文件夹,然后新建axios.js文件

//引入axios 
import axios from 'axios'
//引入element-ui
import {
  Message
} from 'element-ui';
import global_ from '../components/Global'
//引入router
import router from '../router'

// 环境的切换
if (process.env.NODE_ENV == 'development') {
  axios.defaults.baseURL = 'http://127.0.0.1:8090/development';
} else if (process.env.NODE_ENV == 'debug') {
  axios.defaults.baseURL = 'http://127.0.0.1:8090/debug';
} else if (process.env.NODE_ENV == 'production') {
  axios.defaults.baseURL = 'http://127.0.0.1:8090/production';
}

//创建http请求,包括url,消息头,参数
let http = axios.create({
  baseURL: axios.defaults.baseURL,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  },
  transformRequest: [function(data) {
    let newData = '';
    for (let k in data) {
      if (data.hasOwnProperty(k) === true) {
        newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
      }
    }
    return newData;
  }]
});


// http request 拦截器,这里可以加一些token的拦截,具体逻辑可以根据业务需求来定
http.interceptors.request.use(
  config => {
    console.log(config.url);
    if(config.url.indexOf('login') >= 0){
      return config;
    }else{
      let token = sessionStorage.getItem("token");
      if (token) {
        config.headers.token = token;
      }
      return config;
    }
  },
  err => {
    return Promise.reject(err);
  });
//http response 拦截器,根据响应内容作出拦截,例如错误返回登录,token过期等等
http.interceptors.response.use(
  res  => {
    if(res.data.code == 2 || res.data.code == 3){

      Message({
        showClose: true,
        message: '登录信息失效,请重新登录!',
        type: 'error',
        duration: 2000
      })

      //携带当前页面路由,以在登录页面完成登录后返回当前页面
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      });
    }

    if (res.status === 200) {
      return Promise.resolve(res);
    } else {
      return Promise.reject(res);
    }
  },
  err => {
    return Promise.reject(err);
  });

//封装http请求方法,包括get/post,url,参数,响应
function apiAxios(method, url, params, response) {
  http({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
  }).then(function(res) {
    response(res);
  }).catch(function(err) {
    response(err);
  })
}

//调用方法
export default {
  get: function(url, params, response) {
    return apiAxios('GET', url, params, response)
  },
  post: function(url, params, response) {
    return apiAxios('POST', url, params, response)
  },
  put: function(url, params, response) {
    return apiAxios('PUT', url, params, response)
  },
  delete: function(url, params, response) {
    return apiAxios('DELETE', url, params, response)
  }
}

(二)引入axios

在main.js中引入axios


import axios from 'axios'
Vue.prototype.$axios = axios

import Api from './axios/axios.js';
Vue.prototype.$api = Api;

(三)调用

//参数
let params = {
  name: this.addItemForm.name,
  code: this.addItemForm.code,
  type: this.addItemForm.type
}

//this.$api.post调用API
this.$api.post('/xxx/create', params, res => {
  if (res.data.code == 0) {
    this.$message({
      message: '添加成功',
      type: 'success'
    })
  } else {
    this.$message({
      message: '添加失败',
      type: 'error'
    })
  }
});

上一篇:Spring Boot Vue Element入门实战(四)主页面开发
下一篇:Spring Boot Vue Element入门实战(六)常用工具类封装
点击这里返回目录

程序人生,更多分享请关注公众号
在这里插入图片描述

源代码下载

关注上面公众号,回复源码即可获取gitbug/gitee下载地址

猜你喜欢

转载自blog.csdn.net/u013254183/article/details/99292624