头图

WeChat Cloud Hosting is a cloud-native solution provided by the WeChat team and Tencent Cloud team, which is based on cloud-native maintenance-free, high-availability services. It does not require a server, and can deploy a small program/public account server in 1 minute.

Visit https://cloud.weixin.qq.com PC to start using WeChat cloud hosting immediately. New users will be given 3 months of free credit for their first environment.

1. Preparations

Step 1:

Enter WeChat Cloud Hosting, select Mini Program/Official Account to log in.

图片

Step 2: Deploy

At present, WeChat cloud hosting provides two deployment methods, threshold-free deployment and custom deployment. This article will use the no-door-to-door deployment method during initialization;

Select the template in the language you are familiar with, click the "Use" button, and go to the next step. This article will use the Express template for automatic deployment

图片

Cloud hosting will be automatically deployed according to the template content. If there is a dependent database in the template, the database will be automatically activated during deployment

图片

After successful deployment, you can directly access the application in the template through the public domain name, and provide calling code snippets

图片

Application of the counter provided in the template

图片

Second, start to transform

Step 1: Pull code

Official template code portal:

https://github.com/WeixinCloud/wxcloudrun-express

After the pull is successful, the directory files are as follows:

|.dockerignore              
|.gitignore
|container.config.json       
|db.js                      
|Dockerfile                 
|index.html
|index.js
|LICENSE
|package.json
|README.md

Step 2: Use websocket related dependencies

In this article, express-ws is used to build websocket services

express-ws

Step 3:

const path = require('path')
const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const { init: initDB, Counter } = require('./db')

const logger = morgan('tiny')
const app = express();
const expressWs = require('express-ws')(app);
const clients = expressWs.getWss('/').clients
app.ws('/', function (ws, req) { });

app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(cors())
app.use(logger)

// 首页
app.get('/', async (req, res) => {

  res.sendFile(path.join(__dirname, 'index.html'))
})

// 更新计数
app.post('/api/count', async (req, res) => {
  const { action } = req.body
  if (action === 'inc') {
    await Counter.create()
  } else if (action === 'clear') {
    await Counter.destroy({
      truncate: true
    })
  }
  //数据改变后将结果推送至客户端   
  for (let c of clients) {
    c.send(await Counter.count())
  }
  res.send({
    code: 0,
    data: await Counter.count()
  })
})

// 获取计数
app.get('/api/count', async (req, res) => {
  const result = await Counter.count()
  res.send({
    code: 0,
    data: result
  })
})

// 小程序调用,获取微信 Open ID
app.get('/api/wx_openid', async (req, res) => {
  if (req.headers['x-wx-source']) {
    res.send(req.headers['x-wx-openid'])
  }
})



const port = process.env.PORT || 80

async function bootstrap() {
  await initDB()
  app.listen(port, () => {
    console.log('启动成功', port)
  })
}

bootstrap();

through the pipeline (CI/CD)

First upload the modified code to Gitee/GitHub/GitLab, one of the hosting platforms, enter WeChat Cloud Hosting Service Management -> Service List -> Pipeline -> New Pipeline

If the code permission is not authorized or the authorization has expired, please complete the authorization first and then proceed to create the pipeline

图片

After the addition is successful, click Start Pipeline to trigger the deployment, or you can trigger the deployment by checking the push button. When the code is pushed to the specified warehouse, the pipeline will be triggered for code deployment.

图片

Tips: Since the current template uses the database, if you use pipeline triggering, you need to configure the environment variables to container.config.json

{
  "containerPort": 80,
  "dockerfilePath": "Dockerfile",
  "buildDir": "",
  "minNum": 0,
  "maxNum": 10,
  "cpu": 1,
  "mem": 2,
  "policyType": "cpu",
  "policyThreshold": 80,
  "envParams": {
    "MYSQL_ADDRESS": "地址",
    "MYSQL_PASSWORD": "密码",
    "MYSQL_USERNAME": "用户名"
  },
  "customLogs": "stdout",
  "initialDelaySeconds": 2,
  "dataBaseName": "nodejs_demo",
  "executeSQLs": [
    "CREATE DATABASE IF NOT EXISTS nodejs_demo;",
    "USE nodejs_demo;"
  ]
}

Step 5: Write the applet code

The minimum version of the Mini Program base library is 2.21.1
const {
      socketTask
    } = await wx.cloud.connectContainer({
      config: {
        env: '', // 替换自己的微信云托管的环境ID
      },
      service: '', // 替换自己的服务名
      path:'/'
    })
    socketTask.onMessage(function (res) {
      console.log('【WEBSOCKET】', res.data)
    })
    socketTask.onOpen(function (res) {
      console.log('【WEBSOCKET】', '链接成功!')
      setTimeout(() => {
        socketTask.send({
          data: '这是小程序消息'
        })
      }, 5000);
      
    })
    socketTask.onClose(function (res) {
      console.log('【WEBSOCKET】链接关闭!')
    })

Step 6: Start debugging

Open the public network access link for debugging:

图片

Step 7: Debug Results

Now you can see that each click using the counter template in the web will be transmitted to the applet in real time. In this step, the new WebSocket capability provided by WeChat cloud hosting realizes real-time message push:

图片

3. Summary

The above is the new WeChat cloud hosting capability "WebSocket". Based on this new capability, many interesting applications can be extended, such as online chat rooms, collaborative documents, message push, etc., plus some other features of cloud hosting, it is worth experiencing!

Author: Life, senior evangelist for cloud development and cloud hosting. Front-end development engineer, familiar with React and Node.js, has in-depth research in applet and cloud development, and develops multiple commercial applet programs through cloud development and cloud hosting. lecturer.


CloudBase云开发
425 声望438 粉丝

云开发(Tencent CloudBase,TCB)是云端一体化的后端云服务 ,采用 serverless 架构,免去了移动应用构建中繁琐的服务器搭建和运维。同时云开发提供的静态托管、命令行工具(CLI)、Flutter SDK 等能力极大的降...