一,新建一個‘獲取用戶信息’的雲函數
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) )
}
})