微信小程序的请求是基于微信API来实现、所以写了一个独立的 http.js来实现主要的请求如 POST、GET操作,代码如下:
/**
* 请求相关的封装
*/
let baseUrl = "http://xxxxxx.com/api/"; // 接口地址
let header = {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': "Bearer " + wx.getStorageSync("token")
}
/**
* 封装请求
*/
function fetch(options) {
if (options.loading) {
wx.showLoading({
title: '加载中',
mask: true
})
}
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + options.url,
data: options.data,
header: header,
method: options.method,
success: function(res) {
if (options.loading) {
wx.hideLoading()
}
if (res.data.Code == 1) {
// 重新登陆
return false;
}
if (res.data.Code != 0) {
wx.showToast({
title: res.errMsg,
mask: "true",
icon: 'none',
duration: 3000
})
return;
}
resolve(res.data); //把请求到的数据发到引用请求的地方
},
fail: function(err) {
if (options.loading) {
wx.hideLoading()
}
wx.showToast({
title: "网络连接超时",
icon: 'none',
duration: 3000,
})
}
})
})
}
/**
* POST 请求
*/
export function post(url, params, loading = true) {
console.log(params, loading);
var option = {
url: url,
data: params,
method: 'POST',
loading
}
return fetch(option);
}
/**
* GET请求
*/
export function get(urls, params, loading = true) {
console.log(params, loading);
var option = {
url: urls,
data: params,
method: 'GET',
loading
}
return fetch(option);
}
在业务上调用,先通过模块化引入let http = require('../../common/http.js')
小程序官方也推荐使用require非import
使用的时候可以用async await
也可以使用如下方式
Get请求
http.get('getuserInfo', params).then(function (res) {
console.log(res)
})
Post请求
http.post('getuserInfo', params).then(function (res) {
console.log(res)
})
当然其他需要的可以继续扩展,通常业务上的拦截都只能以CODE来做常规操作,如跳转,提示等。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。