开通云开发,配置环境
在app.js里做云开发环境初始化
在pages同级目录下新建文件夹cloud
"cloudfunctionRoot": "cloud/",
右键cloud新建Node.js云函数
在新建的index.js中写云函数
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
const openid = wxContext.OPENID
const action = event.action
let result = {}
switch(action) {
case 'go_login': result.data = await go_login(event.data, openid);
}
return result;
}
//登录函数
async function go_login(data, openid) {
const {
username,
avatarUrl,
sex,
type
} = data
return await db.collection('user').where({
openid
}).get().then(res => {
if (res.data.length != 0) {
return {
code: 200,
tip: '登录成功!',
data: res
}
} else {
return db.collection('user').add({
data: {
username: username,
avatarUrl: avatarUrl,
sex: sex,
type: type,
openid: openid
}
}).then(res => {
return {
code: 200,
tip: '注册成功!',
data: res
}
})
}
})
}
前端代码
go_login() {
if(!this.data.username || !this.data.avatarUrl || !this.data.sex){
wx.showToast({
title: '请完善信息!',
icon: 'none'
})
}else {
let args = {
username: this.data.username,
avatarUrl: this.data.avatarUrl,
sex: this.data.sex,
type: 'user'
}
wx.setStorageSync('args', args)
wx.showLoading({
success: res=>{
wx.cloud.callFunction({
name: 'index',
data: {
action: 'go_login',
data: args
}
}).then(res=>{
wx.hideLoading()
wx.showToast({
title: res.result.data.tip,
icon: 'none'
})
wx.setStorageSync('status', 'user')
setTimeout(() => {
wx.navigateBack();
}, 1000);
})
}
})
}
}