赞
踩
在 util 里面新建 http.js 文件,写入以下内容
const apiUrl = "https://xl.qdscitech.net" function showLoading() { wx.showLoading({ title: '加载中', mask: true }); } function hideLoading() { wx.hideLoading(); } function showErrorToast(message) { wx.showToast({ title: message, icon: 'none', duration: 3000 }); } /** * 封装请求 */ function fetch(options) { if (options.loading) { showLoading(); } return new Promise((resolve, reject) => { wx.request({ url: apiUrl + options.url, data: options.data, header: { "Content-Type": options.contentType }, method: options.method, success: function (res) { if (options.loading) { hideLoading(); } if (res.statusCode !== 200) { showErrorToast("请求失败"); return reject(new Error("Request failed")); } if (res.data.code !== 1) { showErrorToast(res.data.msg); return reject(new Error(res.data.msg)); } resolve(res.data); //把请求到的数据发到引用请求的地方 }, fail: function (err) { if (options.loading) { wx.hideLoading() } showErrorToast("网络连接超时"); reject(err); } }) }) } /** * POST 请求 */ const post = function post(url, params, loading = true, contentType = "application/json") { let option = { url: url, data: params, method: 'POST', loading, contentType } return fetch(option); } /** * GET请求 */ const get = function get(url, params, loading = true) { let option = { url: url, data: params, method: 'GET', loading } return fetch(option); } module.exports = { post, get, apiUrl, }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。