1.执行命令npm install axios --save
2.创建3个文件
在这里插入图片描述
env.js

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

index.js

import Env from './env';
import axios from 'axios'
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 = "登录信息已失效,请重新登录";
      console.log(response.data.msg);
      routerIndex.push('/login');
    }
    if (parseInt(response.data.code) === -1) {
      console.log("请求失败");
    }
  }
  return response;
}, function (error) {
  // Do something with response error
  console.dir(error);
  console.log("服务器连接失败");
  return Promise.reject(error);
})

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

//测试使用
export const ISDEV = Env.isDev;
// 通用方法
export const USER_POST = (url, params) => {
    const getTimestamp = new Date().getTime()
    return axios.post(`${base}${url}?timer=${getTimestamp}`, params).then(res => res.data)
}
//通用方法
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)
}

api_user.js

import * as API from './index'

export default {
  //验证手机号是否已注册
  login: params => {
    return API.USER_POST('xf4g/xfUser/save', params)
},
}

具体调用方式

<button @click="postMethod()">点击这里</button>
postMethod(){
      let params = {
        };
       API.login(params).then(function (res) {
         console.log(res);
       })
    },
Logo

前往低代码交流专区

更多推荐