WeChat Mini Program Cloud Native Development-Quick Start

Advantages of cloud development

  1. Avoid complicated server development process
  2. Can rely on the powerful WeChat team's API library
  3. Convenient for user data management
  4. Conducive to rapid development, low price for small traffic programs, or even free

Tools and preparations for cloud development

Register WeChat Mini Program
Developer Tools: Download URL of Mini Program Developer Tools
Technical Document: Cloud Development Official Document

note

The ID of the applet (AppID) is the only indication of the program developer, and only the corresponding APPID can drive the program to run and test

1. Open cloud development service

Click the "Cloud Development" icon of WeChat Developer Tools, click "Open" in the pop-up box, and after agreeing to the agreement, a dialog box for creating an environment will pop up. At this time, you will be asked to enter the environment name and environment ID, as well as the current basic environment quota for cloud development (the basic quota is free and sufficient for your use).

2. Find the environment ID of cloud development

Click the settings icon in the cloud development console window, and find the environment name and environment ID in the environment variable tab.

When the cloud development service is activated, we can see your environment name in the cloudfunctions folder name of the applet source code. If the name of the cloudfunctions folder is not the environment name, but "unspecified environment", you can right-click the folder, select "More Settings", and then click the "Settings" small icon, select the environment and confirm.

3. Specify the cloud development environment of the applet

Open app.js in the source code folder miniprogram in the developer tools, and find the following code:

wx.cloud.init({
    
    
      // 此处请填入环境 ID, 环境 ID 可打开云控制台查看
      env: 'my-env-id',
      traceUser: true,
    })

在 env: 'my-env-id'处改成你的环境 ID,如 env: 'xly-snoop'

4. Download Nodejs

NodeJS is the runtime environment for running JavaScript on the server, and the server environment used by cloud development is NodeJS. npm is the Node package manager. Through npm, we can easily install the dependency packages needed for cloud development.

npm is an indispensable package (module) manager for front-end development. Its main function is to manage package packages, including installation, uninstallation, update, viewing, searching, publishing, etc. Other programming languages ​​also have similar package managers, such as Python's pip, PHP's composer, Java's maven. We can think of the package manager as the software management center of windows or the application center of mobile phones, but they use a visual interface, and the package manager uses the command line Command Line.

Download link : Nodejs download link

You can download and install the corresponding NodeJS installation package according to the computer's operating system (don't modify the installation directory during installation, and you can install it directly next). Open the computer terminal (cmd command prompt for Windows computer, terminal Terminal for Mac computer), then type line by line and press Enter to execute the following code:

node --version
npm --version

If it shows v10.15.0 and 6.11.3 (maybe your version number will be different), it means that your Nodejs environment has been installed successfully.

Learn programming carefully, don't make mistakes in one letter, one word, and one punctuation mark. Note that when you enter the above command, there is a space after node and npm, and it is two short dashes -.

5. Deploy and upload cloud functions

There is a small cloud in the cloudfuntions folder icon, indicating that this is the root directory of the cloud function. Expand cloudfunctions, we can see that there are login, openapi, callback, echo folders, these are the cloud function directories. The miniprogram folder contains the page file of the mini program.

Cloud functions are placed in cloudfunctions, while miniprograms are placed in the page of miniprograms. This is not static, which means you can also modify the names of these folders, depending on the following in the project configuration file project.config.json Configuration items:

"miniprogramRoot": "miniprogram/",
"cloudfunctionRoot": "cloudfunctions/",

But you'd better keep the folder where the applet page is placed and the folder where the cloud function is placed in a horizontal relationship and both are in the root directory of the project, which is easy to manage.

Use the right mouse button on one of the cloud function directories such as login, and select open in the terminal from the right-click menu. After opening, enter the following code in the terminal and press Enter to execute:

npm install

If it says "npm is not an internal or external command", you need to close the terminal started by the WeChat developer tool, but reopen a terminal window and enter cd /D in your cloud function directory to enter the cloud function directory, such as cd / DC:\download\tcb-project\cloudfunctions\login enter the cloud function directory of login, and then execute the npm install command.

At this time, the dependent module of the cloud function will be downloaded. After the download is complete, right-click the login cloud function directory and click "Create and deploy: all files". At this time, the local cloud function will be uploaded to the cloud. After the upload is successful, log in to the cloud function The directory icon will change to a small cloud.

Click the "cloud development" icon on the toolbar of the developer tools to open the cloud development console, click the cloud function icon in the cloud development console, and you can see our uploaded "login" cloud function in the cloud function list. .

Upload all cloud functions

Next, we follow this process to deploy and upload all other cloud functions (such as openapi), that is, to perform the same steps as above, summarized as follows:

Right-click the cloud function directory, select open in the terminal, and enter the npm install command to download the dependent files;

Then right-click the cloud function directory and click "Create and Deploy: All Files"

Check whether the cloud function is deployed successfully in the cloud development console-cloud function-cloud function list.

Cloud functions such as login, openapi, echo, and callback will be used later. Make sure you deploy and upload successfully. Otherwise, you will get an error when you meet.

Get openid and cloud function login

After we successfully deploy and upload the cloud function login, we can click to get openid in the simulator and mobile phone (you need to re-click the preview icon and scan the QR code).

6. Get openid and call cloud function

openid is the unique identifier of the applet user, that is, every applet user has a unique openid. Click "click to get openid", if "user id obtained successfully" and a string of letters + numbers are displayed on the user management guide page, it means that your login cloud function is deployed and uploaded successfully. If obtaining openid fails, you need to resolve the deployment and upload of the login cloud function before proceeding to the following steps.

Interpretation of calling cloud functions

The homepage of the applet is "pages/index/index", which can be seen from the configuration items of app.json or the page path in the lower left corner of the simulator. There is this code in index.wxml:

Click to get openidbutton>
that is, when you click the "click to get openid" button, the event handler onGetOpenid bound to bindtap will be triggered. You can see the onGetOpenid event handler in index.js (Find the event handler onGetOpenid in index.js Comparative understanding) The wx.cloud.callFunction() interface is called (open technical documents for comparative understanding)

Technical document: call cloud function wx.cloud.callFunction

The method of calling a cloud function is very simple. You only need to fill in the name of the cloud function (here is login) and the parameters that need to be passed (there are no upload parameters here), and then you can call. Add the following code in the success callback function to print the res object:

console.log('调用login云函数返回的res',res)

Remember to save the code after adding it. If the file modification is not saved, there will be a small green dot on the tab page. You can use the shortcut keys (press at the same time) Ctrl and S to save (Command and S for Mac computers).

After compiling, click the "click to get openid" button to see the complete res object. The res object has three parameters:

  1. requestID: Cloud function execution ID, which can be used to find logs in the cloud development console, and open the cloud development console – Cloud Function – Log. Here you can filter and view the call log of the cloud function (including the return result) based on the cloud function function name and requestID );

  2. result: The result returned by the cloud function. The result returned by the login cloud function contains the appid and event objects. We can access them through res.result.appid and res.result.event;

  3. errMsg: Shows whether the cloud function is successfully called. After the
    event processing function onGetOpenid successfully calls the cloud function, three things are done:

Use console.log to print openid, you can click the button to trigger the cloud function and see the print result in the console;

Assign the obtained appid to the globalData global object in the app.js file;
jump to the userConsole page;

The userConsole page just takes out the openid from globalData and renders it to the page through setData.

Initial experience of cloud development

New cloud function

Right-click the cloud function root directory of the cloud function, and select the new Node.js cloud function in the pop-up window. For example, enter sum and press Enter to confirm. The WeChat developer tool will create the sum cloud function directory locally (your computer). The corresponding cloud function will be created in the online environment (that is, automatically deployed, you can see it in the cloud function list of the cloud development console)

Open index.js in the sum cloud function directory, add sum:event.a+event.b, to the return function (the extra content can be deleted), and then remember to select the cloud function incremental upload: (update file) , Update the sum cloud function.

 return {
    
    
    sum:event.a+event.b,
  }

The a and b are variables, but unlike the previous one, we did not declare a and b on the server side. This is because we can declare variables on the small program side.

Click "Quickly create a new cloud function" in the developer tool simulator, it will jump to the addFunction page, open addFunction.wxml, we see that the test cloud function is bound to the testFunction event processing function.

<view class="list-item" bindtap="testFunction">
  <text> 测试云函数</text>
</view>

Let's look at the testFunction in addFunction.js to see how the variables a and b are related to the server-side variables, and how the results are rendered to the page. testFunction calls the cloud function sum through wx.cloud.callFunction, the difference is that there are a and b in data:

data: {
    
    
  a: 1,
  b: 2
},

The data filled in are the parameters passed to the cloud function, that is, the parameters of the applet are first passed to the cloud function, and then the cloud function is processed and then the res object is returned. We can print the res object in the success callback function:

console.log("sum云函数返回的对象",res)

After compiling, we click on the test cloud function again, and we can see the printed result in the console, and the result.result.sum is 3. Directly assign result.result.sum to result through setData to render the number, then what is this result.result? What is JSON.stringify()?

result: JSON.stringify(res.result)

We can print out result.result, and JSON.stringify(res.result)

console.log("What is res.result", res.result)
console.log("What is JSON.stringify(res.result)", JSON.stringify(res.result))
res.result is an object, and JSON .stringify(res.result) is in json format. The JSON.stringify() method converts a JavaScript value (object or array) into a JSON string, because if the object is directly rendered to the page, it will display [object Object].

Transformation of traditional projects into cloud development projects

Of course, we can also transform the projects that did not use cloud development in the previous chapters to use cloud services. First, create a new folder in the root directory of the applet, such as cloudfunctions, and then add the path configuration of the cloud function folder in project.config.json Yes,

"cloudfunctionRoot": "cloudfunctions/",

Then create a new miniprogram folder, and put the other files of the mini program except project.config.json, such as pages, utils, images, app.js, app.json, etc., into the miniprogram folder, and then put it in project.config .json add miniprogramRoot configuration:

"cloudfunctionRoot": "cloudfunctions/",
"miniprogramRoot":"miniprogram/",

It is worth mentioning that if the cloud function is successfully deployed and uploaded, we can always call it. As long as the appid and environment ID of your applet have not changed, no matter how many applet projects you create, you can directly call the deployed cloud function. For example, the previous login, echo, callback, sum and other cloud functions. That is to say, once the cloud function is successfully deployed, it will always be in the cloud server, even if you delete all the local cloud functions of the applet, it doesn't matter.

When the cloud function root directory is created and configured as the cloudfunctions folder, there is no cloud function in the cloud function root directory. We can right-click the cloud function root directory cloudfunctions folder to select the synchronization cloud function list, and all cloud functions in the cloud can be selected The list is all listed (this is just a list), and to modify the content of the cloud function, we can right-click on one of the cloud function directories and choose to download the cloud function.

In addition, we need to use the life cycle function onLaunch of the app.js of the applet

wx.cloud.init()来初始化云开发能力:
onLaunch: function () {
    
    
    if (!wx.cloud) {
    
    
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
    
    
      wx.cloud.init({
    
    
        env: '你的环境ID',
        traceUser: true,
      })
    }
  },

The global cloud development capability only needs to be initialized once. The traceUser attribute here is set to true, and the user access will be recorded in the user management. The access record can be seen in the operation analysis-user access of the cloud development console.

Guess you like

Origin blog.csdn.net/david2000999/article/details/114809467