由于wx.request的请求是异步的,所以如果我们有两个要执行的方法,两个方法中都通过执行wx.request请求处理数据,且方法的执行有前后关系,这时我们就需要使用同步操作
一、方法一
app.js文件中代码如下
App({
onLaunch: function(){
},
getToken: function(){
let _this = this;
return new Promise(function(resolve, reject){
wx.checkSession({
success: function (res) { resolve(res); },
fail: function (res) {
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
wx.request({
url: CONFIG.loginUrl,
data: {
code: res.code
},
header: {
'shopId': CONFIG.shopId
},
method: 'POST',
success: res => {
wx.setStorageSync('token', res.data); //储存返回的token
resolve(res);
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg);
reject('error');
}
}
})
}
})
})
}
})
要使用的页面中的js文件
const app = getApp();
Page({
onLoad: function(){
let token = wx.getStorageSync('token');
if (token == ''){
//第一次登录,获取登录状态
app.getToken().then(function (res) {
_this.getData(); //此时token必然已经获取到,且getData()在此时才会执行
})
}else{
//有token的情况直接获取数据
_this.getData();
}
},
//获取数据
getData: function(){
wx.request({
header: {
'token': wx.getStorageSync('token')
},
url: 'https://xxxxx.xxxxx',
method: 'GET',
success: res => {
console.log(res);
}
})
}
})
方法二、封装wx.request
//封装wx.request()
function request(requestMapping, data, requestWay, contentType) {
wx.showLoading({
title: '请稍后',
})
return new Promise(function(resolve, reject) {
console.log('请求中。。。。。')
wx.request({
url: '自己的服务器地址' + requestMapping,
data: data,
header: {
'content-type': contentType // 默认值
},
timeout: 3000,
method: requestWay,
success(res) {
//console.log(res)
if (res.data.success == false || res.data.statusCode == 404) {
reject(res)
} else {
resolve(res)
}
},
fail: (e) => {
wx.showToast({
title: '连接失败',
icon: 'none'
})},
complete: () => {
wx.hideLoading()
}
})
})
}
//获取openid
function getOpenId(app, that){
return new Promise(function (resolve, reject) {
wx.login({
success: function (yes) {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
var requestMapping = '/testopenid'
var data = {
code: yes.code
}
var requestWay = 'GET'
var contentType = 'application/json'
var p =request(requestMapping, data, requestWay, contentType)
p.then(res => {
//console.log(res) 做一些后续操作
app.globalData.openId = res.data;
resolve(res)
}).catch(e => {
reject(e)
})
},
fail(e) {
console.log(e)
}
})
})
}
ps:java后端获取openid的示例代码
@RequestMapping("/testopenid")
public String getUserInfo(@RequestParam(name = "code") String code) throws Exception {
System.out.println("code" + code);
String url = "https://api.weixin.qq.com/sns/jscode2session";
url += "?appid=xxxxxxxxxxxxx";//自己的appid
url += "&secret=xxxxxxxxxxxxxxxxxxx";//自己的appSecret
url += "&js_code=" + code;
url += "&grant_type=authorization_code";
url += "&connect_redirect=1";
String res = null;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// DefaultHttpClient();
HttpGet httpget = new HttpGet(url); //GET方式
CloseableHttpResponse response = null;
// 配置信息
RequestConfig requestConfig = RequestConfig.custom() // 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000) // 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000) // socket读写超时时间(单位毫秒)
.setSocketTimeout(5000) // 设置是否允许重定向(默认为true)
.setRedirectsEnabled(false).build(); // 将上面的配置信息 运用到这个Get请求里
httpget.setConfig(requestConfig); // 由客户端执行(发送)Get请求
response = httpClient.execute(httpget); // 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
res = EntityUtils.toString(responseEntity);
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + res);
}
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
JSONObject jo = JSON.parseObject(res);
String openid = jo.getString("openid");
System.out.println("openid" + openid);
return openid;
}
参考文章:https://developers.weixin.qq.com/community/develop/article/doc/000c80906b4210625f3bde3775bc13
原创文章,作者:witersen,如若转载,请注明出处:https://www.witersen.com