vue request.js封装及使用

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
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值