微信小程序 云開(kāi)發(fā) -- 云函數(shù)
查看項(xiàng)目根目錄下 project.config.json 文件敏沉,是否存在cloudfunctionRoot
{
"cloudfunctionRoot": "cloudfunctions/",
}
云函數(shù)根目錄上右鍵狐史,在右鍵菜單中纫普,可以選擇創(chuàng)建一個(gè)新的 Node.js 云函數(shù)
我們將該云函數(shù)命名為 add
開(kāi)發(fā)者工具在本地創(chuàng)建出云函數(shù)目錄和入口 index.js 文件,同時(shí)在線上環(huán)境中創(chuàng)建出對(duì)應(yīng)的云函數(shù)。創(chuàng)建成功后,工具會(huì)提示是否立即本地安裝依賴蹄殃,確定后工具會(huì)自動(dòng)安裝 [wx-server-sdk
]
云函數(shù)的結(jié)構(gòu):
// 云函數(shù)入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
return event.a + event.b
}
在云函數(shù)目錄上右鍵,在右鍵菜單中你踩,我們可以將云函數(shù)整體打包上傳并部署到線上環(huán)境中
小程序中調(diào)用該云函數(shù)
onReady: function() {
let that = this;
wx.cloud.callFunction({
// 云函數(shù)名稱
name: 'add',
// 傳給云函數(shù)的參數(shù)
data: {
a: 7,
b: 2,
},
success: function(res) {
console.log(res.result) // 3
that.setData({
sum: res.result
})
},
fail: console.error
})
},