微信小程序封装wx.request方法
wx.request(object)
| 参数名 | 类型 | 是否必填 | 默认值 | 详细说明 |
|---|---|---|---|---|
| url | string | 是 | 接口地址 | |
| data | Object/String/ArrayBuffer | 否 | 接口需要的入参 | |
| header | Object | 否 | 设置请求的 header,header 中不能设置 Referer。 | |
| method | string | 否 | get | 有效值:options, get, head,post,put,delete,trace, connect |
| dataType | string | 否 | json | 如果设为json,会尝试对返回的数据做一次 JSON.parse |
| responseType | string | 否 | text | 设置响应的数据类型。合法值:text、arraybuffer |
| success | Function | 否 | 成功返回的回调函数 | |
| fail | Function | 否 | 用失败的回调函数 | |
| complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
具体详情请访问:https://developers.weixin.qq.com/minigame/en/dev/api/network/request/wx.request.html
wx.request方法封装
js文件中(例如util.js文件):
/* 公共request 方法 */const requestUrl=({ url, params, success, method="post"})={ wx.showLoading({ title: '加载中', }); let server = 'https://developers.weixin.qq.com';//正式域名 // let server = 'http://dxxx.xxxxxxxxxx.cn';//测试域名 let sessionId=wx.getStorageSync("sid"), that=this; if (sessionId != "" && sessionId !=null){ var header = { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'sid=' + sessionId } }else{ var header = { 'content-type': 'application/x-www-form-urlencoded'} } return new Promise(function (resolve, reject) { wx.request({ url: server + url, method: method, data: params, header: header, success: (res) = { wx.hideLoading(); if (sessionId == "" || sessionId == null) { wx.setStorageSync('sid', res.data.info.sessionId)// 如果本地没有就说明第一次请求 把返回的 sessionId 存入本地 } if (res.data.result === 'error' || res['statusCode']!==200) { wx.showToast({ title: res.data.msg || '请求出错', icon: 'none', duration: 2000, mask: true }) } resolve(res.data) }, fail: function (res) { wx.hideLoading(); wx.showToast({ title: res.data.msg || '', icon: 'none', duration: 2000, mask: true }) reject(res.data) }, complete: function () { wx.hideLoading() } }) }) .catch((res) = { })}/* 公共showTotast loading 方法 */module.exports = { formatTime: formatTime, requestUrl: requestUrl}调用封装的方法
const util = require('../../utils/util.js') util.requestUrl({ url: "接口路径",//不需要域名,因为方法中已经拼接域名 data:{}, method:"post", success:function(res){ console.log(res) } })













