1,创建函数目录
首先,我们在项目中创建一个云函数目录,路径随意,我的是functions
2,修改manifest.json
代码如下:
"mp-weixin" : {
"appid" : "wx*******", // 小程序id
"cloudfunctionRoot": "./functions/",
"setting" : {
"urlCheck" : false,
"minified" : true
},
"usingComponents" : true
},
3. 编写vue.config.js
在根目录下创建vue.config.js 代码如下(如路径不一样请做相应适配):
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
configureWebpack: {
plugins: [
new CopyWebpackPlugin([
{
from: path.join(__dirname, 'functions'),
to: path.join(__dirname, 'unpackage/dist', process.env.NODE_ENV === 'production' ? 'build' : 'dev', process.env.UNI_PLATFORM, 'functions')
}
])
]
}
}
如果没有安装copy-webpack-plugin插件,请先安装插件
请注意插件版本,如果版本不对可能会出现如下错误:
编译报错ERROR TypeError: compilation.getLogger is not a function
或者:
Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options[0] misses the property 'patterns'. Should be:
[non-empty string | object { from, to?, context?, globOptions?, toType?, force?, flatten?, transform?, cacheTransform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)
ValidationError: Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
npm install --save-dev copy-webpack-plugin@5.0.0
已向数据库添加数据为例:
在微信开发者工具中在 function 文件下右击选择 新建Node.js云函数 如下图:
创建funcadd 会生成index.js 文件和文件,为了方便编辑将文件夹复制到HBuilder X编辑器中
index.js 内容如下
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
return db.collection(event.dataBaseName).add({ // event.dataBaseName 传递的集合的名字
data:event.data, // 需要向数据库插入的参数
})
}
调用云函数
wx.cloud.callFunction({
name: 'funcadd', // 函数名字
data: {
dataBaseName:'user_base', // 集合的名字
data:{ // 插入的数据
name: "测试2",
age:18,
sex:'女'
}
},
success(_res) {
console.log(_res)
},
fail(_res) {
console.log(_res)
}
})