‘content-type‘: isJson ? ‘application/json‘ : ‘application/x-www-form-urlencoded‘
const requests = require("../utils/request.js")
module.exports = {
// 登录
wxLogin: (data) => {
return requests.Request("/wx/login/wx-login.json", { jsCode: data }, ‘post‘, true);
},
//获取用户信息
getUserInfo: (data) => {
return requests.Request("/wx/login/get-user-info.json", data, ‘post‘, true);
},
//获取用户手机号
getUserPhone: (data) => {
return requests.Request("/wx/login/get-user-phone.json", data, ‘post‘, true);
}
}
3.修改下app.js
const userRequest = require("/api/user.js")
App({
onLaunch: function () {
// 展示本地存储能力
var logs = wx.getStorageSync(‘logs‘) || []
logs.unshift(Date.now())
wx.setStorageSync(‘logs‘, logs)
wx.setStorageSync(‘url‘, "http://localhost:8087");
this.getUserInfo();
},
onShow() { },
getUserInfo() {
let that = this;
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
userRequest.wxLogin(res.code).then((res) => {
if (res.code === "SUCCESS") {
wx.setStorageSync(‘sessionKey‘, res.data.sessionKey);
that.globalData.userInfo = res.data.wxUser;
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (that.userInfoReadyCallback) {
that.userInfoReadyCallback(res.data.wxUser)
}
} else {
wx.showToast({
title: ‘登录失败‘,
icon: ‘none‘,
duration: 2000,
mask: true
})
}
});
}
})
},
globalData: {
userInfo: null
}
})
4.别的页面调用
onLoad: function () {
let that = this;
wx.getSetting({
success: function (res) {
if (res.authSetting[‘scope.userInfo‘]) {
//用户授权了
that.setData({
isShowAuth: false
})
that.initData();
} else {
//用户还没授权,弹出授权窗
that.setData({
isShowAuth: true
})
}
}
})
}
5.