Introduction to cloud development of wechat applet value

Posted by TheCase on Fri, 18 Feb 2022 17:06:21 +0100

1, Applet cloud development

Cloud development of applications:

Developers can use cloud development to develop wechat applets and games. They can use cloud capabilities without building a server.

Cloud development provides developers with complete native cloud support and wechat service support, weakens the concept of back-end and operation and maintenance, does not need to build a server, and uses the API provided by the platform for core business development to realize rapid online and iterative. At the same time, this ability is compatible with the cloud services already used by developers and is not mutually exclusive.

Cloud development provides several basic capabilities:

Cloud functionNo self built server is requiredThe code running in the cloud is naturally authenticated by wechat private protocol. Developers only need to write their own business logic code
databaseNo self built database is requiredA JSON database that can not only operate in the front end of the applet, but also read and write in the cloud function
storageNo need for self built storage and CDNUpload / download cloud files directly at the front end of the applet and manage them visually on the cloud development console
Cloud callNative wechat service integrationThe ability to use the open interface of applet without authentication based on cloud function, including the ability to call the server and obtain open data

1.1 create project

Open and log in the wechat developer tool, create a new applet project, fill in the AppID, select "applet · cloud development" for the back-end service, and check and agree to the "cloud development service terms":

1.2 cloud development

Before using cloud development capability, you need to open cloud development.

On the left side of the toolbar of the developer tool, click the "cloud development" button to open the cloud console, open cloud development according to the prompt, and create a new cloud development environment.

  • Each environment is isolated from each other and has a unique environment ID, including independent database instances, storage space, cloud function configuration and other resources;
  • The initially created environment automatically becomes the default environment;
  • Two environments can be created under the default quota

1.3 setting up cloud environment

Cloud Development Directory

The cloud environment to be set here is the cloud environment used during development or program running. If the selection is wrong, the cloud function created earlier may not be found

Open app js

We need to configure the env and traceUser fields

The env cloud ID represents our current environment selection

After traceUser is set to true, our operations can be visible in the log

1.4 start development

After opening the creation environment, you can start operating applets on the simulator to experience some basic capability demonstrations provided by cloud development

We open the cloud development console

1.4.1 database

Cloud development provides a JSON database. As the name suggests, each record in the database is an object in JSON format.
A database can have multiple sets (equivalent to tables in relational data). The set can be regarded as a JSON array. Each object in the array is a record, and the format of the record is JSON object.

1.4.2 database operation

1. Initialization (call to get the reference of the database of the default environment)

 const db =

2. Get the reference of a collection through the collection method on the database reference

const todos = db.collection('Collection name')

3. Call the add method on the collection object to insert a record into the collection

exports.main = async (event, context) => {
  let res = await db.collection('todos').add({
      desc:'I am the newly inserted data',
      due:new Date(),
  return res

4. Use the update method to update only the specified fields, and other fields are not affected.

exports.main = async (event, context) => {
  try {
    return await db.collection('Collection name').where({
      name : 'alice'
      data: {

5. Use the remove method to delete the record

exports.main = async (event, context) => {
  try {
    return await db.collection('Collection name').where({
      name : 'alice'

1.5 writing cloud functions

Write cloud functions, query the database and return data

Create a new cloud function music and write the following code

// Cloud function entry file
const cloud = require('wx-server-sdk')

  env: 'test-2gw33xcpbb0f6b27',
  traceUser: true,

const db = cloud.database()
// Cloud function entry function
exports.main = async (event, context) => {
  // console.log(event)
  let res = await db.collection('todos').where({
  return res

Note: cloud Init method needs configuration parameters, especially env. Otherwise, it may always prompt "database collection not exists" during the test

1.6 cloud development local debugging error

Cannot find module 'wx-server-sdk'

This mistake doesn't matter how he came here

You only need to open the terminal in the current cloud function directory

npm install --save wx-server-sdk@latest

1.7 cloud function routing

The cloud function of each control is limited, so we should try to use each cloud function and write the business-related code into a cloud function

Therefore, the cloud function here is different from the api in conventional background development

  • The function of each api should be as single as possible
  • Each cloud function should handle as many tasks as possible. Of course, these tasks are related, such as recommended song list, popular song list, music search, etc


  • The role of routing is to allocate user requests to different controllers for processing
  • In this way, although many methods are written in a controller, they can be called by the correct request through routing
  • The cloud function should also have the same response mechanism to allocate different requests of users to different processes


Note: cloud function installation

npm install --save tcb-router

Introduced in cloud function

const TcbRouter=require('tcb-router')

Modify cloud function code

// Cloud function entry file
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
env: 'test-5gngkp7l028ba32b',
traceUser: true,
// Cloud function entry function
exports.main = async (event, context) => {
	const app = new TcbRouter({ event });
	app.router('playlist', async (ctx, next) => {
	let res = await cloud.database().collection('playlist')
		.orderBy('createTime', 'desc')
	ctx.body = res
// await next(); //  Execute next Middleware
return app.serve();

Reference in page

    let res = await{

Topics: Javascript Front-end Mini Program