vue封装axios及axios模块化使用

1,首先在根目录下新建文件夹utils,然后新建文件request.js
在这里插入图片描述
2,在 request.js中统一处理axios请求

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'

//创建一个axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests//在跨域请求时发送cookie
      // 所有的请求都会带上这些配置,比如全局都要用的身份信息等。
      headers: {
        'Content-Type': 'application/json'
        // 'token_in_header': global_.token,//token从全局变量那里传过来
      },
    timeout: 5000 // request timeout
  })

  // response interceptor//响应拦截器
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
    */
  
    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
  //    / **
  //    *如果您想获取标题或状态等http信息
  //    *请返回响应=>响应
  //   * /
  
  //   / **
  //    *通过自定义代码确定请求状态
  //    *这只是一个例子
  //    *您还可以通过HTTP状态代码判断状态
  //    * /
    response => {
      const res = response.data
      
  
      // if the custom code is not 20000, it is judged as an error.
      if (!res.success) {
        console.log(res)
        Message({
          message: res.msg || 'error',
          type: 'error',
          duration: 5 * 1000
        })
  
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          // to re-login
          MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }
        return Promise.reject(res.message || 'error')
      } else {
         return Promise.resolve(response)
      }
    },
    error => {
      console.log('err' + error) // for debug
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  )
  
  export default service

3,在根目录下创建api文件夹,此文件夹为接口文件夹
在这里插入图片描述
4,然后在api文件夹新建文件user.js,这里放登录接口,不同类别接口创建不同的js文件

import request from '@/utils/request'   //引入封装的axio函数

export function login(data) {   //请求接口
  return request({
    url: '/api/ucenter/sys/login',
    method: 'post',
    data
  })
}

export function getInfo(token) {
  return request({
    url: '/user/info',
    method: 'get',
    params: { token }
  })
}

5,在Login.vue中引用登录接口

import { login } from "../../api/user";
//请求接口
 let loginParams = {
            loginName: this.ruleForm.username,
            password: this.ruleForm.password
          };
          this.loading = true;
          login(loginParams)
            .then(res => {
              console.log(res.loginUser.sessionId);
              this.$router.push('/dashboard');
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值