uni-app学习:使用微信云函数的步骤

3 篇文章 0 订阅
1 篇文章 0 订阅

1,创建函数目录

首先,我们在项目中创建一个云函数目录,路径随意,我的是functions
函数目录路径

2,修改manifest.json

配置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)
	}
})
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值