import {Cookie} from "./cookie"; /** * 微信网络请求接口的封装,使其能够支持简单的cookie保存发送功能 */ export class Session { cookies = {} constructor(){ } set_cookie(cookie){ this.cookies[cookie.key] = cookie; } get cookie_str(){ let cookie_strs = Object.values(this.cookies).map(cookie=>cookie.toString()); return cookie_strs.join(";"); } request({url, data, header, method, dataType, responseType, success, fail, complete}) { console.log("request data and headers: "); console.log({url: url, data: data, header: {...header, "Cookie": this.cookie_str}, method: method, dataType: dataType, responseType: responseType}) return wx.request({ url: url, data: data, header: {...header, "Cookie": this.cookie_str}, method: method, dataType: dataType, responseType: responseType, success: (res) => { if ("cookies" in res) { let cookies = res["cookies"]; for (var i = 0; i < cookies.length; i++) { this.set_cookie(new Cookie(cookies[i])); } console.log("set new cookies:"); console.log(this.cookies); } else { console.warn("request.js: no cookies setted in this request"); } if (typeof success == "function") { success(res); } else { console.warn("requests.session.request.success is not function"); } }, fail: fail, complete: complete }); } uploadFile({url, filePath, name, header, formData, success, fail, complete}){ return wx.uploadFile({ url: url, filePath: filePath, name: name, header: {...header, "content-type": "multipart/form-data", "Cookie": this.cookie_str}, formData: formData, success: success, fail: fail, complete: complete }) } downloadFile({url, header, filePath, success, fail, complete}){ return wx.downloadFile({ url: url, header: {...header, "Cookie": this.cookie_str}, filePath: filePath, success: success, fail: fail, complete: complete }) } }