当前位置: 首页 > 工具软件 > Escapes.js > 使用案例 >

vue request.js封装及使用

袁枫涟
2023-12-01

1、request.js代码部分

import axios from "axios";
import $store from "../store";
import toLogin from "@libs/login";
import {
	VUE_APP_API_URL
} from "@utils/index";

const instance = axios.create({
	baseURL: VUE_APP_API_URL,
	timeout: 3000
});

const defaultOpt = {
	login: true
};

function baseRequest(options) {
	const token = $store.state.app.token;
	console.log($store.state.app);
	const headers = options.headers || {};
	headers["Authori-zation"] = "Bearer " + token;
	options.headers = headers;
	if (options.login && !token) {
		toLogin();
		return Promise.reject({
			msg: "未登录",
			toLogin: true
		});
	}
	console.log(options);
	return instance(options).then(res => {
		const data = res.data || {};
		if (res.status !== 200)
			return Promise.reject({
				msg: "请求失败",
				res,
				data
			});

		if ([410000, 410001, 410002].indexOf(data.status) !== -1) {
			toLogin();
			return Promise.reject({
				msg: res.data.msg,
				res,
				data,
				toLogin: true
			});
		} else if (data.status === 200) {
			return Promise.resolve(data, res);
		} else {
			return Promise.reject({
				msg: res.data.msg,
				res,
				data
			});
		}
	});
}

/**
 * http 请求基础类
 * 参考文档 https://www.kancloud.cn/yunye/axios/234845
 *
 */
const request = ["post", "put", "patch"].reduce((request, method) => {
	/**
	 *
	 * @param url string 接口地址
	 * @param data object get参数
	 * @param options object axios 配置项
	 * @returns {AxiosPromise}
	 */
	request[method] = (url, data = {}, options = {}) => {
		return baseRequest(
			Object.assign({
				url,
				data,
				method
			}, defaultOpt, options)
		);
	};
	return request;
}, {});

["get", "delete", "head"].forEach(method => {
	/**
	 *
	 * @param url string 接口地址
	 * @param params object get参数
	 * @param options object axios 配置项
	 * @returns {AxiosPromise}
	 */
	request[method] = (url, params = {}, options = {}) => {
		return baseRequest(
			Object.assign({
				url,
				params,
				method
			}, defaultOpt, options)
		);
	};
});

export default request;

2、@libs/login

import router from "../router";
import store from "../store";
import cookie from "@utils/store/cookie";
import { isWeixin } from "@utils";
import { oAuth } from "@libs/wechat";

export default function toLogin(push, backUrl) {
  store.commit("LOGOUT");
  const { fullPath, name } = router.currentRoute;
  cookie.set("login_back_url", backUrl || fullPath);
  if (isWeixin()) {
    oAuth();
  } else {
    if (name !== "Login") {
      push
        ? router.push({ path: "/login" })
        : router.replace({ path: "/login" });
    }
  }
}

@utils/store/cookie 、wechat 请见:附加1
@utils见:3、@utils/index代码部分

3、@utils/index代码部分

export function trim(str) {
  return String.prototype.trim.call(str);
}

export function isType(arg, type) {
  return Object.prototype.toString.call(arg) === "[object " + type + "]";
}

export function isWeixin() {
   return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
}

export function parseQuery() {
  const res = {};

  const query = (location.href.split("?")[1] || "")
    .trim()
    .replace(/^(\?|#|&)/, "");

  if (!query) {
    return res;
  }

  query.split("&").forEach(param => {
    const parts = param.replace(/\+/g, " ").split("=");
    const key = decodeURIComponent(parts.shift());
    const val = parts.length > 0 ? decodeURIComponent(parts.join("=")) : null;

    if (res[key] === undefined) {
      res[key] = val;
    } else if (Array.isArray(res[key])) {
      res[key].push(val);
    } else {
      res[key] = [res[key], val];
    }
  });

  return res;
}
//${location.origin}
const VUE_APP_API_URL =
  process.env.VUE_APP_API_URL || ``;
//http://fengmi.hanwuji.mobi/api
const VUE_APP_WS_URL =
  process.env.VUE_APP_WS_URL || `ws:${location.hostname}:20003`;

export { VUE_APP_API_URL, VUE_APP_WS_URL };

4、api.js调用


export function getBargainUserList(data) {
  return request.get("/bargain/user/list", data);
}

export function getBargainUserCancel(data) {
  return request.post("/bargain/user/cancel", data);
}

附加1

1、cookie.js 封装

import { trim, isType } from "@utils";

const doc = window.document;

function get(key) {
  if (!key || !_has(key)) {
    return null;
  }
  let regexpStr =
    "(?:^|.*;\\s*)" +
    escape(key).replace(/[-.+*]/g, "\\$&") +
    "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";
  return JSON.parse(unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")));
}

function all() {
  let cookies = doc.cookie.split(/; ?/g),
    data = {};
  for (let i = cookies.length - 1; i >= 0; i--) {
    if (!trim(cookies[i])) {
      continue;
    }
    let kvp = cookies[i].split("=");
    let key = unescape(kvp[0]);
    data[key] = unescape(kvp[1]);
  }
  return data;
}

function set(key, data, time) {
  if (!key) {
    return;
  }
  let expires = "Tue, 19 Jan 2038 03:14:07 GMT";
  if (time) {
    let date;
    if (isType(time, "Date")) {
      date = time;
    } else {
      date = new Date();
      date.setTime(date.getTime() + time * 60000);
    }
    expires = date.toGMTString();
  }

  data = JSON.stringify(data);
  doc.cookie =
    escape(key) + "=" + escape(data) + "; expires=" + expires + "; path=/";
}

function remove(key) {
  if (!key || !_has(key)) {
    return;
  }
  doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
}

function clearAll() {
  Object.keys(all()).forEach(function(key) {
    remove(key);
  });
}

function _has(key) {
  return new RegExp(
    "(?:^|;\\s*)" + escape(key).replace(/[-.+*]/g, "\\$&") + "\\s*\\="
  ).test(doc.cookie);
}

export default {
  get,
  all,
  set,
  remove,
  clearAll,
  has: _has
};

 类似资料: