赞
踩
wx.request({ url: "https://www.escook.cn/api/get", //请求的接口地址,必须基于 https协议 method: "GET", // 请求方法 data: { // 发送到服务器的数据 name: "zs", age: 18, }, success: (res) => { // 请求成功之后的回调函数 console.log(res); }, fail: (error) => { // 请求失败的回调函数 console.log(error); }, });
wx.request({ url: "https://www.escook.cn/api/post", //请求的接口地址,必须基于 https协议 method: "POST", // 请求方法 data: { // 发送到服务器的数据 name: "zs", age: 18, }, success: (res) => { // 请求成功之后的回调函数 console.log(res); }, fail: (error) => { // 请求失败的回调函数 console.log(error); }, });
/** * 封装一个Promise风格的通用请求 * option - 包含请求地址、请求方式、请求参数、请求头、是否加载、是否需要Token */ var app = getApp(); //引入全局app.js,我们可以在globalData中定义一些公用的数据,比如baseUrl、token import Toast from "/@vant/weapp/toast/toast"; //引入vant插件,用于提示错误 export const request = function (options) { const method = (options.method || "GET").toUpperCase(); const { url, data, header = {}, isToken = true, isLoading = true } = options; return new Promise((resolve, reject) => { if (isLoading) { wx.showLoading({ title: "加载中...", mask: true, }); } wx.request({ url: app.globalData.baseUrl + url, method, // content-type 默认为 application/json 所以当方法不是GET方式需要转为JSON字符串 data: method === "GET" ? data : JSON.stringify(data), // header这里根据业务情况自行选择需要还是不需要 header: isToken ? { ...header, Authorization: "Bearer " + app.globalData.token } : header, success: (res) => { if (res.data.code === 0) { resolve(res); } else { Toast(res.data.msg); reject(res.data.msg); } }, fail: (err) => { reject(err); }, complete: () => { if (isLoading) { wx.hideLoading(); } }, }); }); };
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。