axios配置及使用(发起请求时带上token)

1.安装

利用npm安装

npm install axios --save

2.引入即可使用

import axios from 'axios'

3.目录

 

4.各个文件设置:

(1)env.js

export default {
  // 接口地址
  baseURL: 'http://localhost:8090/scheduleweb/',
  isDev: true
}

(2)index.js

备注:road.js定义了一个新的Vue对象,目的是调用elementUI的提示信息($message,比如当服务器连接失败时,提示“服务器连接失败”),不需要用到的可移除相关配置

import Env from './env';
import axios from 'axios'
import {road} from '../road.js'
import routerIndex from '../router/index'

let token = '';

axios.defaults.withCredentials = false;
axios.defaults.headers.common['token'] = token;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';//配置请求头

//添加一个请求拦截器
axios.interceptors.request.use(function (config) {
  let user = JSON.parse(window.sessionStorage.getItem('access-user'));
  if (user) {
    token = user.token;
  }
  config.headers.common['token'] = token;
  //console.dir(config);
  return config;
}, function (error) {
  // Do something with request error
  console.info("error: ");
  console.info(error);
  return Promise.reject(error);
});

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
  if (response.data && response.data.code) {
    if (parseInt(response.data.code) === 108 || parseInt(response.data.code) === 109 || response.data.msg === 'TOKEN失效,请重新登录' || response.data.msg === 'TOKEN不存在') {
      //未登录
      response.data.msg = "登录信息已失效,请重新登录";
      road.$message.error(response.data.msg);
      routerIndex.push('/login');
    }
    if (parseInt(response.data.code) === -1) {
      road.$message.error("请求失败");
    }
  }
  return response;
}, function (error) {
  // Do something with response error
  console.dir(error);
  road.$message.error("服务器连接失败");
  return Promise.reject(error);
})

//基地址
let base = Env.baseURL;

//测试使用
export const ISDEV = Env.isDev;

//通用方法
export const POST = (url, params) => {
  const getTimestamp = new Date().getTime();
  return axios.post(`${base}${url}?timer=${getTimestamp}`, params).then(res => res.data)
}

export const GET = (url, params) => {
  const getTimestamp = new Date().getTime();
  return axios.get(`${base}${url}?timer=${getTimestamp}`, {params: params}).then(res => res.data)
}

export const PUT = (url, params) => {
  return axios.put(`${base}${url}`, params).then(res => res.data)
}

export const DELETE = (url, params) => {
  return axios.delete(`${base}${url}`, {params: params}).then(res => res.data)
}

export const PATCH = (url, params) => {
  return axios.patch(`${base}${url}`, params).then(res => res.data)
}

(3)api_user.js 

         该文件具体展示调用方法

import * as API from './'

export default {
  //验证手机号是否已注册
  isExistUser: params => {
    return API.GET('login/isExistUser', params);
  },
  //注册
  register: params => {
    return API.POST('login/userRegister', params)
  },
  //密码登录
  login: params => {
    return API.POST('login/userLogin', params)
  }
}

5.在组件中调用

import API from '../api/api_user'
import md5 from 'js-md5'

export default {
  data() {
    return {
      loading: false
    }
  },
  methods: {
    login() { // 登录
      let that = this;
      that.loading = true; // 按钮点击后设置loading
      let params = { // 参数
        userName: "user1",
        pwd: md5("123456"),
        type: 3
      }
      // 调用接口
      API.login(params).then(function (res) {
        if (res.code === 0) {
          let userInfo = {
            id: res.data.user.id,
            mobilePhone: res.data.user.mobilePhone,
            nickname: res.data.user.userName,
            gender: res.data.user.gender,
            photo: res.data.user.photo,
            token: res.data.token,
            timestamp: new Date().getTime()
          };
          localStorage.setItem('access-user', JSON.stringify(userInfo)); // 将用户信息存到localStorage中
          that.$router.replace({path: '/'}); // 登录成功跳转
        } else {
          that.loading = false;
          that.$message.error(res.msg);// elementUI消息提示
        }
      });

    }
  }
}

 

posted @ 2018-10-25 17:06  Lena_叶  阅读(44491)  评论(2编辑  收藏  举报