一,新建一个‘获取用户信息’的云函数
1,首先新建一个cloudfunction目录,然后再配置project.config.json
“cloudfunctionRoot”: “cloudfunction/”,
"description": "项目配置文件",
"cloudfunctionRoot": "cloudfunction/",
"packOptions": {
"ignore": []
},
2,右击cloudfunction目录,新建node.js云函数,命名getinfo
index.js
// 云函数入口文件
const cloud = require('wx-server-sdk')
//初始化
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
return event
}
3,最后右击getinfo目录,上传云函数
二,使用云函数获取用户信息
app.js
/**云资源 */
wx.cloud.init() //初始化
const db = wx.cloud.database()
//测试getInfo云函
wx.cloud.callFunction({
name: 'getInfo',
complete: res => {
that.globalData.openid = res.result.userInfo.openId;
console.log('that.globalData.openid=' + that.globalData.openid)
}
})
三,新建云函数操作服务端api(更新用户信息)
像一些 where 等条件搜索等api在本地是无法运行的,需要在云端使用云函数操作数据
1,新建一个updateUserInfo云函数
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()
try {
return await db.collection('Users').where({
_openid: wxContext.OPENID
})
.update({
data: {
comp_name: event.comp_name,
comp_sex: event.comp_sex,
comp_email: event.comp_email,
comp_mobile: event.comp_mobile,
comp_work_pcp: event.comp_work_pcp,
comp_work_address: event.comp_work_address,
comp_img: event.comp_img,
},
})
} catch (e) {
console.error(e)
}
}
个人信息修改页js
<表单验证成功后,把value更新到云数据库>
//云函
wx.cloud.callFunction({
name: 'updateUserInfo',
data: {
comp_name: e.detail.value.comp_name,
comp_sex: e.detail.value.comp_sex,
comp_email: e.detail.value.comp_email,
comp_mobile: e.detail.value.comp_mobile,
comp_work_pcp: that.data.citykey,
comp_work_address: that.data.address,
},
complete: res => {
console.log('updateUserInfo=' + JSON.stringify(res) )
}
})