当前位置:   article > 正文

基于axios给请求添加token_axios 添加token

axios 添加token

基于axios封装

创建js文件

import axios from "axios";
import { baseURL } from '../utils/config.js'     //请求的地址
if (process.env.NODE_ENV === 'development') {
  baseURL;
} else {
  baseURL;
}

//创建自定义axios对象
const instance = axios.create({
  baseURL,
  timeout: 30000,
})


// 增加请求拦截器
instance.interceptors.request.use(
  config => {
    // console.group('本次请求的地址为:', config.url)
    // 给headers添加token属性
    if (sessionStorage.getItem('Token')) {
      config.headers.token = sessionStorage.getItem('Token');
    }
    // alert('解决');
    // alert(JSON.stringify(config))
    // if (store.state.meteoToken) {
    //     config.headers.Authorization = store.state.meteoToken;
    // }
    return config
  },
  error => {
    // loadingCount = 0;
    // if (loadingInstance) {
    //     loadingInstance.close();
    // }
    // alert('这里写警示框弹出的内容');
    return error;
  }
)
//暴露get
export function get (url, params = null) {
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params,
    }).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err);
    });
  })
}

//暴露post  
export function post (url, params, isFile = false) {
  let data = params;
  //处理请求头
  let config = {
    Headers: { "Content-Type": "application/json" }
  }

  //处理文件
  if (isFile) {
    data = new FormData();
    for (let i in params) {
      data.append(i, params[i])
    }
    //处理有文件时请求头
    config = {
      Headers: {
        "Content-Type": "multiple/form-data"
      }
    }
  }
  // alert('ewuhshgjsnfsj'); 
  return new Promise((resolve, reject) => {
    instance.post(url, data, config).then(res => {
      resolve(res.data);
    }).catch(err => {
      // alert(err)
      reject(err)
    })
  })
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84

封装之后可以直接引用该js文件中的get、post

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/886515
推荐阅读
相关标签
  

闽ICP备14008679号