Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cloud Development Cloud Access and HTTP Triggering


May 22, 2021 Mini Program Cloud Development Advanced



Cloud access is an HTTP access service for developers based on cloud functions, and developers can easily access all resources within the cloud development environment through HTTP requests using POST, PUT, GET, DELETE, etc. without the need for a Web-side SDK. A nd cloud access naturally supports cross-domain requests, adding a domain name to a Web secure domain name, which allows web pages to access cloud access across domains. When using cloud functions, the system automatically provisions the TLS certificate, so we can call the cloud function over a secure connection.

First, use cloud access to access cloud functions

Enabling cloud access for cloud functions is very simple, and we can use Tencent Cloud to develop a web console and cloudbase Cli commands.

1, cloud development console to start cloud access

Open the cloud function menu of Tencent Cloud Development Web Console, then click on the HTTP trigger tab, turn on HTTP trigger, cloud access will start, the default domain name of cloud access is https://{你的环境id}.service.tcloudbase.com/

In the previous we have uploaded a webtest cloud function (other cloud functions can also oh), click into the management page of the webtest cloud function, then click on the /webtest save, open the following link in the browser (the web console directly linked) to access the cloud access:

  1. https://{你的环境id}.service.tcloudbase.com/webtest

You can compare the objects that are event, context objects, and objects returned by calling cloud functions. When a cloud function is called with cloud access, http requests are converted into a special structure called an integration request, as follows:

  1. {
  2. path: 'HTTP请求路径,如 /hello',
  3. httpMethod: 'HTTP请求方法,如 GET',
  4. headers: {HTTP请求头},
  5. queryStringParameters: {HTTP请求的Query,键值对形式},
  6. requestContext: {云开发相关信息},
  7. body: 'HTTP请求体',
  8. isBase64Encoded: 'true or false,表示body是否为Base64编码'
  9. }

The queryStringParameters The Quary of http://www.queryParameters, and we can pass in some parameters in the link, such as some parameters in the link to access cloud access:

  1. https://xly-xrlur.service.tcloudbase.com/webtest?name=bbsky&location=shenzhen

2, using Cloudbase Cli to start cloud access

As we learned earlier, by cloudbase --help at the terminal, we can see what the commands for Cloudbase Cli are (although cloudbase is global and we recommend that you do it at the root of a cloud development project), and we can see that the commands for cloud access are:

  1. service:switch [options] 开启/关闭 HTTP Service 服务
  2. service:auth:switch [options] 开启/关闭 HTTP Service 服务访问鉴权
  3. service:create [options] 创建 HTTP Service
  4. service:delete [options] 删除 HTTP Service
  5. service:list [options] 获取 HTTP Service 列表
  6. service:domain:bind [options] <domain> 绑定自定义 HTTP Service 域名
  7. service:domain:unbind [options] <domain> 解绑自定义 HTTP Service 域名
  8. service:domain:list [options] 查询自定义 HTTP Service 域名

From these commands, we can enter the following commands in the terminal to turn cloud access on and off, such as turning on cloud access services with the cloud development environment xly-xrlur

  1. cloudbase service:switch -e xly-xrlur

Between the following commands, we can create a cloud access route with /webtest and a cloud function as webtest:

  1. cloudbase service:create -p /webtest -f webtest

In addition to using the browser to open a link to cloud access, we can also use the cURL command line to invoke cloud access, for example, we can enter the following commands at the terminal:

  1. curl https://xly-xrlur.service.tcloudbase.com/webtest

3, the incoming parameters and get summary

It is necessary to re-check the incoming and acquisition-related knowledge of some parameters, how do we pass in parameters into the cloud function by calling the cloud function, by adding configuration information when accessing the cloud access link, and by configuring the cloud function environment? (There is also through the require module, files, not much here to introduce)

Call the incoming parameters of the cloud function

On the small terminal, the Web side, and the cloud function side, we can call the cloud function through the callFunction interface (the small terminal is wx.callFunction, the cloud function side is cloud.callFunction, and the web side is app.callFunction) and pass in parameters:

  1. wx.cloud.callFunction({
  2. name: 'webtest', //被调用的云函数的名称
  3. data: {
  4. userInfo:{
  5. name:"李东bbsky"
  6. },
  7. id:"20200420001"
  8. }
  9. })

So how do we get the parameters that are passed when we call a cloud function? We can copy from the object:

  1. const {userInfo,id} = event

Pass in parameters when accessing the cloud access link

We can also pass parameters to cloud functions by accessing https such as cloud access links or axios, which we can pass through in the quryString Parameters object

  1. const {name,title} = event.queryStringParameters

Cloud function configuration information is passed in to the parameters

We can configure the cloud function with some parameters in the cloud development console, that is, the field of the new environment variable, which is obtained in the cloud function as follows:

  1. const {school,name} = process.env

Second, background functions and cloud access

With the concept of cloud access, we can divide cloud functions into two categories, in the previous chapter cloud functions are mainly used to call cloud functions, processing databases, cloud storage cloud calls, we can call it a background function, and HTTP functions are we can call through the standard HTTP request.

Refer to the web cloud development in the last section, create a new cloud function such as backfunction in the functions folder, and then enter the following code in the index.js, noting that a dbName parameter is passed in by the HTTP request:

  1. const tcb = require('@cloudbase/node-sdk')
  2. tcb.init({
  3. env: "xly-xrlur"
  4. })
  5. const db = tcb.database()
  6. const _ = db.command
  7. exports.main = (event,context) =>{
  8. const {dbName} = event.queryStringParameters //注意queryStringParameters的来源
  9. return db.collection(dbName)
  10. .where({
  11. gdp: _.gt(3000)
  12. })
  13. .get()
  14. }

Then install the dependency of the cloud function, upload the code deployment of the cloud function to the cloud, and turn on cloud access and set up the route, the specific operation is described earlier, and then we open the following link in the browser, you can see the data returned by the cloud function.

  1. http://xly-xrlur.service.tcloudbase.com/backfunction?dbName=china

On the small terminal we know that getting wx.request() while on the web side we can use axios, in statically hosted html pages, such as index.html in the public folder before opening, entering the following code, then opening the link, and then the browser console can get the data:

  1. <script src="https://unpkg.com/axios/dist/axios.min.js" rel="external nofollow" ></script>
  2. <script>
  3. const url ="https://xly-xrlur.service.tcloudbase.com/backfunction?dbName=china"
  4. axios.get(url).then(res => {
  5. console.log(res)
  6. console.log(res.data)
  7. }).catch(err => {
  8. console.log(err)
  9. })
  10. </script>

Third, return the integration response

Cloud functions can return data of String, Object, Number, and so on, as well as integration responses, and cloud access converts the return value into a normal HTTP response, and we then use cloud access to return some static resource files.

1, using the integrated response to return HTML

Use VS Code to create a new cloud function in the fusions folder, such as sendhtml, and the assats folder, which holds the HTML files we want to return, as follows:

  1. ├── sendhtml //sendhtml云函数目录
  2. └── assets
  3. └── index.html
  4. └── index.js
  5. └── config.json
  6. └── package.json

Then enter the following code in the index .js, read the index.html in the cloud function directory .html, and return HTML, which is very different from previous cloud functions:

  1. const tcb = require('@cloudbase/node-sdk')
  2. tcb.init({
  3. env: "xly-xrlur"
  4. })
  5. const fs = require('fs')
  6. const path = require('path')
  7. exports.main = async (event,context) =>{
  8. //path.resolve() 方法将路径或路径片段的序列解析为绝对路径
  9. const html = fs.readFileSync(path.resolve(__dirname, './assets/index.html'), {
  10. encoding: 'utf-8'
  11. })
  12. return {
  13. statusCode: 200,
  14. headers: {
  15. 'content-type': 'text/html'
  16. },
  17. body: html
  18. }
  19. }

In the asats folder index.html you can enter some html code, then deploy the sendndhtml cloud function to upload and turn on cloud access, and set up /sendhtml the address of cloud access with the browser, the returned HTML is automatically resolved by the browser.

2. Use the integrated response to return other types of files

In addition to html files, other types of files can be returned, and in response, the Content-Type entity header is used to indicate the MIME media type of the resource, telling the Web side the type of content returned. There are many types of media, such as:

Type Describe A typical example
text Normal text type text/plain , text/html , text/css , text/javascript
image The type of image image/gif , image/png , image/jpeg , image/bmp , image/webp , image/x-icon , image/vnd.microsoft.icon
audio The audio file audio/midi , audio/mpeg, audio/webm, audio/ogg, audio/wav
video The video file video/webm , video/ogg
application Binary data

By setting content-type to application/javascript, text/css, JavaScript files and css files can be returned in body, and html, js, and css files are the core files of static sites, all of which can be returned, so that a complete static site can be returned with an integrated response. Note the difference between static sites returned with integration requests and static hosting.

By setting the content-type to image/png and isBase64Encoded to true, you can return the binary of the picture, which can also be used in combination with cloud storage. For example, we can write the following cloud functions, first download the picture inside the cloud storage, turn Buffer into a base64 format picture, and then return, so that we can view the picture through the link to the cloud access:

  1. const cloud = require('wx-server-sdk')
  2. cloud.init({
  3. env: "xly-xrlur"
  4. })
  5. exports.main = async (event,context) =>{
  6. const fileID = 'cloud://xly-xrlur.786c-xly-xrlur-1300446086/1572315793634-953.png'
  7. const res = await cloud.downloadFile({
  8. fileID: fileID,
  9. })
  10. const buffer = res.fileContent
  11. const base64img = await buffer.toString('base64')
  12. return {
  13. isBase64Encoded: true,
  14. statusCode: 200,
  15. headers: {
  16. 'content-type': 'image/png'
  17. },
  18. body: base64img
  19. }
  20. }