vue 接口的4种请求方式

request封装,在接口访问的时候执行

import 'babel-polyfill'
import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
import qs from 'qs'
import { clearLoginInfo } from '@/utils'
import isPlainObject from 'lodash/isPlainObject'

const http = axios.create({
    baseURL: window.SITE_CONFIG['apiURL'],
    timeout: 1000 * 180,
    withCredentials: true
})


/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
    config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
    if (config.url !== '/oauth/token') {
        config.headers['Authorization'] = 'Bearer ' + Cookies.get('access_token') || ''
    }
    // 默认参数
    var defaults = {}
        // 防止缓存,GET请求默认带_t参数
    if (config.method === 'get') {
        config.params = {
            ...config.params,
            ... { '_t': new Date().getTime() }
        }
    }
    if (isPlainObject(config.params)) {
        config.params = {
            ...defaults,
            ...config.params
        }
    }
    if (isPlainObject(config.data)) {
        config.data = {
            ...defaults,
            ...config.data
        }
        if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
            config.data = qs.stringify(config.data)
        }
    }
    return config
}, error => {
    return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {

    if (response.data.code === 401 || response.data.code === 10001) {
        clearLoginInfo()
        router.replace({ name: 'login' })
        return Promise.reject(response.data.msg)
    }

    return response
}, error => {
    console.error(error)
    return Promise.reject(error)
})

export default http

 封装的接口也能写加token

import request from "@/router/axios";

/**获取信息用get
提交信息用post
修改信息用put
删除用delete
基本就这几个常用**/

import { baseUrl } from "@/config/env";
//get 用params
export const getTeamTree = (params) =>
  request({
    url: baseUrl + "/api/team/tree",
    method: "get",
    params: params
});
//post 用data接收
export const addTeam = (data) => {
  return request({
    url: baseUrl + "/api/team/tree",
    method: "post",
    data: data
  });
};
//put 用data接收
export const updateTeam = (data) => {
  return request({
    url: baseUrl + "/api/team/tree",
    method: "put",
    data: data
  });
};
//delete 拼接id的方式
export const removeTeam = (id) => {
  return request({
    url: baseUrl + "/api/team/tree/" + id,
    method: "delete"
  });
};
//delete 传id数组的方式

export const removeMember = (ids) => {
  return request ({
      url: baseUrl + '/api/team/number',
      method:"delete",
      data: ids
  })
}
//分页
export const getTeamPage = (page, limit, params) => {
  return request({
    url: baseUrl + "/api/team/number/page",
    method: "get",
    params: {
      page,
      limit,
      ...params
    }
  });
};

export const exportMember = (params) => {
  return request({
    url: baseUrl + "/api/team/number/export",
    method: "post",
    params: {
      ...params
    }
  });
};

export const getSysBusiDictData = (type) =>
  request({
    url: baseUrl + `/api/sys/sysBusiDictData/${type}`,
    method: "get"
});

由于request封装好了,额外需要接口传token,为了不造成access_token有值刷新就能跳转近项目首页,所以单独使用axios方式,如下:

 
      axios({
        method:'put',
        url:baseUrl+'/api/sys/user/password',
        headers: {
          'Authorization': `bearer ${Cookies.get('edit_token')}` //传token
        },
        data: params,
      }).then(res => {
         if(res.data.code == 0){
            goToLogin();
         }else{
          ElMessage.error(res.data.msg);
         }
      })

在控制台如何看是否传token?

env.js
 

// 阿里矢量图标库配置
let iconfontVersion = ["567566_pwc3oottzol"];
let iconfontUrl = `//at.alicdn.com/t/font_$key.css`;

let baseUrl = "";
let appUrl = "";
let uploadUrl="";
let codeUrl = `${baseUrl}/code`;
let imgUrl="";
let loginOutUrl = "";
const env = process.env;
if (env.NODE_ENV === "development") {
  baseUrl = `/our-user`; // 开发环境地址
  appUrl = `/upload`;
  uploadUrl = `/el/upload`;
  //图片显示
  imgUrl = "http://192.168.10.11:18090/upload";
  loginOutUrl = "http://localhost:3000/";
} else if (env.NODE_ENV === "production") {
  baseUrl = ``; //生产环境地址
} else if (env.NODE_ENV === 'dev') {
  // 开发环境
  baseUrl = ``;
  appUrl = ``;
  uploadUrl = ``;
  imgUrl = "http://192.168.10.11:18090/upload";
  loginOutUrl = "http://192.168.10.11:18090/";
} else if (env.NODE_ENV === 'test') {
  // 测试环境
  baseUrl = ``;
  appUrl = ``;
  uploadUrl = ``;
  imgUrl = "";
  loginOutUrl = "";
} 
//自行配置开发测试环境路由
export { baseUrl, appUrl,uploadUrl,iconfontUrl,imgUrl,iconfontVersion, codeUrl, env, loginOutUrl };