1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| const _ = require("./lodash");
class Request { constructor(parms) { this.withBaseURL = parms.withBaseURL; this.baseURL = parms.baseURL; } get(url, data, customParams) { return this.request("GET", url, data, customParams); } post(url, data, customParams) { return this.request("POST", url, data, customParams); } put(url, data, customParams) { return this.request("PUT", url, data, customParams); } delete(url, data, customParams) { return this.request("DELETE", url, data, customParams); } request(method, url, data, customParams = {}) { const vm = this; const withBaseURL = _.startsWith(url, "http") ? false : vm.withBaseURL; return new Promise((resolve, reject) => { wx.request({ url: withBaseURL ? vm.baseURL + url : url, data, method, header: { Cookie: wx.getStorageSync("Cookie"), }, ...customParams, success(res) { setCookie(res); const statusCode = res.statusCode; if (statusCode !== 200) { reject({ statusCode: statusCode, msg: "请求失败", url: withBaseURL ? vm.baseURL + url : url, method, data, err: _.get(res, "data"), }); } else { resolve(res); } }, fail(err) { reject({ msg: "请求失败", url: vm.withBaseURL ? vm.baseURL + url : url, method, data, err: err, }); }, }); }); } }
const mode = "dev";
const apiUrl = `https://${mode === "prod" ? "" : mode}api.yoursite.com`;
const commonRequest = new Request({ baseURL: apiUrl, withBaseURL: true, });
const setCookie = (data) => { let cookieArr = []; if (_.get(data, `header['Set-Cookie']`)) { const cookieOriArr = data.header["Set-Cookie"].match(/([\w\-.]*)=([^\s=]+);/g) || []; _.forEach(cookieOriArr, (str) => { if (!/path=|domain=|samesite=|max-age=/gi.test(str)) { cookieArr.push( _.endsWith(str, ";") ? str.substring(0, str.length - 1) : str ); } });
let localCookie = wx.getStorageSync("Cookie") || ""; let CookieObj = {}; const localCookieArr = localCookie.split(";") || [];
_.forEach(_.compact(localCookieArr), (item) => { const cookieItem = item.split("="); CookieObj[cookieItem[0]] = cookieItem[1]; });
_.forEach(_.compact(cookieArr), (item) => { const cookieItem = item.split("="); CookieObj[cookieItem[0]] = cookieItem[1]; });
const CookieStr = _.map(_.keys(CookieObj), (key) => { return `${key}=${CookieObj[key]}`; }).join(";"); wx.setStorageSync("Cookie", CookieStr); } };
module.exports = { commonRequest, setCookie, };
|