封装request

安装axios:
npm i axios -S
在utils/request.js

import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url基础地址,解决不同数据源url变化问题
  // withCredentials: true, // 跨域时若要发送cookies需设置该选项
  timeout: 5000 // 超时
});

// 请求拦截
service.interceptors.request.use(
  config => {
    // do something
    const token = localStorage.getItem('token')
    if (token) {
      // 设置令牌请求头
      config.headers["Authorization"] = 'Bearer ' + token;
    }
    return config;
  },
  error => {
    // 请求错误预处理
    //console.log(error) // for debug
    return Promise.reject(error);
  }
);

// 响应拦截
service.interceptors.response.use(
  // 通过自定义code判定响应状态,也可以通过HTTP状态码判定
  response => {
    // 仅返回数据部分
    const res = response.data;

    // code不为1则判定为一个错误
    if (res.code !== 1) {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000
      });

      // 假设:10008-非法令牌; 10012-其他客户端已登录; 10014-令牌过期;
      if (res.code === 10008 || res.code === 10012 || res.code === 10014) {
        // 重新登录
        MessageBox.confirm(
          "登录状态异常,请重新登录",
          "确认登录信息",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload();
          });
        });
      }
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  error => {
    //console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;

根目录创建.env.development

# base api
# VUE_APP_BASE_API = '/dev-api'
VUE_APP_BASE_API = 'http://127.0.0.1:7300/mock/5d786f7c8d7eac40b82e9538/vue-study'

src/api/user.js

import request from '@/utils/request'

export function login(data) {
  return request({
    url: '/user/login',
    method: 'post',
    data
  })
}

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

vue.config.js
before那段是mock数据
安装一下body-parser
npm i body-parser

const port = 7070;
const title = "vue项目实践";
const path = require("path");
const bodyParser = require("body-parser");

function resolve(dir) {
  return path.join(__dirname, dir);
}

module.exports = {
  publicPath: "/best-practice",
  devServer: {
    port,
    proxy: {
      // 代理 /dev-api/user/login 到 http://127.0.0.1:3000/user/login
      [process.env.VUE_APP_BASE_API]: {
        target: `http://127.0.0.1:3000/`,
        changeOrigin: true,
        pathRewrite: {// /user/info   /dev-api/user/info  /user/info  
          ["^" + process.env.VUE_APP_BASE_API]: "",
        },
      },
    },
    // before: app => {
    //     app.use(bodyParser.json());
    //     app.use(
    //       bodyParser.urlencoded({
    //         extended: true
    //       })
    //     );

    //     app.post("/dev-api/user/login", (req, res) => {
    //       const { username } = req.body;

    //       if (username === "admin" || username === "jerry") {
    //         res.json({
    //           code: 1,
    //           data: username
    //         });
    //       } else {
    //         res.json({
    //           code: 10204,
    //           message: "用户名或密码错误"
    //         });
    //       }
    //     });

    //     app.get("/dev-api/user/info", (req, res) => {
    //       const auth = req.headers["authorization"];
    //       const roles = auth.split(' ')[1] === "admin" ? ["admin"] : ["editor"];
    //       res.json({
    //         code: 1,
    //         data: roles
    //       });
    //     });
    //   }
  },
  configureWebpack: {
    name: title,
  },
  chainWebpack(config) {
    // 1.让已有svgloader排除掉icons目录
    config.module.rule("svg").exclude.add(resolve("src/icons"));

    // 2.新增svg-sprite-loader
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({ symbolId: "icon-[name]" });
  },
};

store/modules/user.js

import {login, getInfo} from '@/api/user';

// 用户状态:登录态、信息
const state = {
  token: localStorage.getItem("token"),
  // 其他用户信息
  roles: [],
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
};

const actions = {
  // 模拟用户登录
  login({ commit }, userInfo) {
    // const { username } = userInfo;
    // 调用并处理结果,错误处理已拦截无需处理
    return login(userInfo).then((res) => {
      commit("SET_TOKEN", res.data);
      localStorage.setItem("token", res.data);
    });
    // return new Promise((resolve, reject) => {
    //   setTimeout(() => {
    //     if (username === "admin" || username === "jerry") {
    //       commit("SET_TOKEN", username);
    //       localStorage.setItem("token", username);
    //       resolve();
    //     } else {
    //       reject("用户名、密码错误");
    //     }
    //   }, 1000);
    // });
  },
  getInfo({ commit, state }) {
    return getInfo(state.token).then(({data: roles}) => {
      commit("SET_ROLES", roles);
      return {roles}
    })
    // return new Promise(resolve => {
    //   setTimeout(() => {
    //     const roles = state.token === "admin" ? ["admin"] : ["editor"];
    //     commit("SET_ROLES", roles);
    //     resolve({ roles });
    //   }, 1000);
    // });
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      localStorage.removeItem("token");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};

你可能感兴趣的:(封装request)