May 22, 2021 Mini Program Cloud Development Advanced
The environment for cloud development can also develop web applications, including ordinary PC pages or pages in public numbers, and even if background services are required during the development process, there is no need to build servers, and cloud capabilities provided by cloud development can be used directly. Developers don't have to worry about specific back-office resources and operations, they can quickly go online and iterate using the APIs provided by the platform for core business development.
How do we initialize cloud development in static web pages when we've created a cloud development project on-premises with
Cloudbase init
on our computers with cloudbase Cli tools, and we've started static site hosting?
Use an editor, such as Visual Studio Code, to open the project folder tcbweb, which you created earlier, and then use VS Code to create a new public folder and create a new one inside the public folder
The directory structure of the final folder is as follows, and a clear project file structure facilitates our orderly development management:
.
├── _gitignore
├── functions // 云函数目录
│ └── app
│ └── index.js
├── public // 用于存放应用程序的静态文件
│ └── index.html
│ └── js
│ └── main.js
│ └── css
│ └── style.css
│ └── assert
└── cloudbaserc.js // 项目配置文件
In the previous we have introduced the computer terminal, Visual Studio Code also has a terminal, can also be in this terminal command line operation of the terminal, and the computer terminal slightly different, we can also choose according to the habits.
Then use VS Code to open the index.html file, VS Code editor built-in set of emmet syntax, can greatly improve the efficiency of our writing HTML code, in index .html input an exclamation point in English state!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web端云开发</title>
</head>
<body>
Web端云开发页面内容
</body>
</html>
Then add the head tag to the following, adding the cloud development web side SDK, which is .js to the web application:
<head>
<!-- 省略-->
<script src="https://imgcache.qq.com/qcloud/tcbjs/1.7.0/tcb.js" rel="external nofollow" ></script>
<script src="./js/main.js"></script>
</head>
Note the version number
1.7.0
which is not necessarily up-to-date, and it is recommended that the tcb-js-sdk npm package address get the latest version number, especially if new features are required. W e can also download the latest version of the Web-side SDK by introducing thenpm install --save tcb-js-sdk@latest
andconst tcb = require("tcb-js-sdk");
Bringing the Web-side SDK into your project is not much of a introduction here.
Use VS Code to open the main.js file under the js folder, in which you can enter the following code to complete the initialization of the cloud development environment, and small program cloud development, to call the resources in the cloud development environment, you need to initialize, init is used to set up the call cloud functions, databases, file storage to access the environment.
const app = tcb.init({
env: '你的环境ID' // 此处填入你的环境ID
});
We know that the configuration file cloudbaserc.js or cloudbaserc.json under the project root also needs to be filled in the environment ID, this profile is mainly used for project management, this and the initialized Web-side environment is somewhat different Oh, pay attention.
That is to say, we want to initialize cloud development capabilities, one is to introduce the Web side SDK tcb.js file, and the other is to initialize the Web side environment, these two are essential Oh, after the introduction of these two, cloud development capabilities even if the initialization is completed.
To debug Web cloud development on your on-premises computer, you need to do the following in addition to installing the Nodejs environment on your computer, installing cloudbase Cli tools, and initializing cloud development projects.
Use the account developed by the small program cloud to log in to the Tencent cloud development console, that is, when you log in, select WeChat public number to log in, then use the small program cloud development administrator's WeChat Broom, select one of the environments in the cloud development console, enter the management page of the environment, click on the environment-environment settings menu, select the login method tab, and then:
In the login mode can choose to start anonymous login, anonymous login is somewhat similar to the game's tourist access mode, users do not need to register to obtain and store data, this way is more convenient for us to do local debugging.
There is only one anonymous user per device at the same time, and this user never ends (if the user manually clears the device or browser's local data, the anonymous user's data is synchronously purged, and calling the anonymous login API again results in a new anonymous user). There are no more than 10 million anonymous users per environment.
Open the previously created .js and add the following code after the environment initialization to enable anonymous login. Window.onload is similar to the onLoad lifecycle function of a small program lifecycle, and when pages that include styles, images, and other resources are all loaded, the load event on the window object is triggered.
window.onload = function(){
app.auth({
persistence: 'session' //在窗口关闭时清除身份验证状态
})
.anonymousAuthProvider()
.signIn() //AnonymousAuthProvider.signIn() 匿名登录云开发
.then(() => {
console.log("登录成功") //登录成功
}).catch(err => {
console.log("登录失败",err) //登录失败
})
env: 'xly-xrlur' // 此处填入你的环境ID
});
Add
localhost:5000
secure domain names at
web
secure domain names so that pages under that domain name can use the SDK to access cloud development services.
If you want to access your static hosting site through other ports or domain name addresses in localhost, you'll need to add them all to the list of secure domain names.
To open the terminal, let's start by installing the packageserve globally (note the installation rights solution mentioned earlier, before the Mac PC command plus sudo, Windows wants to open the terminal as an administrator):
npm install -g serve
Then run the following command at the root of the project (note that the cloudbaserc .js is located in the root) to open a local static server:
npx serve
When successful, the service is turned on and the local host port address, as well as the ip address, which can be accessed by the browser on your local computer. E
nter a browser
http://localhost:5000/public/
and you'll .html index.
Open the browser's developer tool and see the log that signed in successfully on the Console tab, indicating that the anonymous login was successful
It is recommended to use Chrome, right-click on the "Review Element" (MacBook for "Check") in the blanks of the index.html page, and we can open Chrome's developer tool and we can debug the code on the Console tab.
For debugging convenience, we can not close the terminal window of
npx serve
to perform other tasks can reopen a terminal window.
When we update the index, main, .html files .js the public folder, we refresh the pages in the browser directly.
We open another terminal window, then enter the project root via the cd command, and then enter the following command at the terminal to upload all the files below the public folder to the folder of the static hosting site, such as to the web folder
xly-xrlur
cloudbase hosting:deploy ./public web -e xly-xrlur
We can then access the page in the browser by opening the secondary
二级域名/web
your domain
你的域名/web
and we can also view the print log of the page using the browser's developer tool console.
Calling the Web side SDK is not limited to static managed services that come with cloud development, we can also use other static hosting services such as Github Pages, or we can also use web pages developed by traditional development, that is, as long as the web also introduces sdk, and adds secure domain names, etc., we can also use cloud development services.
Web cloud development can not only call the cloud functions you create in the small program cloud development, we can also create cloud functions locally and deploy to the cloud development environment for the Web side and small terminal to call, that is, the cloud functions in the cloud development environment are common to the Web side and the small terminal, how the small terminal creates and deploys cloud functions everyone should be familiar with, the web side uses vscode to create and deploy cloud functions and use WeChat developer tools is the same reason.
We can build a folder under the functions folder in the root of the web-end cloud development project, which is the same as the root of the small-program cloud development cloud function, as well as the same three new files and the contents of the copy (as we do every time we create a cloud function), such as our new webtest cloud function, whose directory structure is as follows:
├── _gitignore
├── functions // 云函数根目录
│ └── app //app云函数目录
│ └── index.js
│ └── config.json
│ └── package.json
│ └── webtest //webtest云函数目录
│ └── index.js //主体结构和小程序云开发云函数里的index.js一样
│ └── config.json //copy小程序云开发云函数里的config.json
│ └── package.json //copy小程序云开发云函数里的package.json
├── public // 用于存放应用程序的静态文件
│ └── index.html
│ └── js
│ └── main.js
│ └── css
│ └── style.css
│ └── assert
└── cloudbaserc.js // 项目配置文件
In the index .js we can enter the following code, introduce service-side sdk, initialize the service-side environment, and return data in the main function:
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: '你的环境ID'
})
const auth = app.auth()
exports.main = async (event, context) => {
const ip = auth.getClientIP() //获取客户端ip
const {
openId, //微信openId,非微信授权登录则空
appId, //微信appId,非微信授权登录则空
uid, //用户唯一ID
customUserId //开发者自定义的用户唯一id,非自定义登录则空
} = auth.getUserInfo()
return {"event对象":event,
"context对象":context,
"客户端ip":ip,
"openId":openId,
"appId":appId,
"uid":uid,
"customUserId":customUserId
}
}
The cloud function created on the web side here, we can neither use the web-side SDK @cloudbase/node-sdk, or follow the writing of small program cloud development, using wx-server-sdk, if cross-terminal development suggests the latter.
Then use the terminal to open the cloud function directory,
npm install
to install the dependency that depends on the package.json, and then add the configuration of the webtest cloud function to the functions of the cloudbaserc.js
functions
for example:
{
name: "webtest",
timeout: 5,
envVariables: {},
runtime: "Nodejs10.15",
handler: "index.main"
},
Upload cloud function deployments to the cloud using the Cloudbase Cli tool:
cloudbase functions:deploy webtest
Here are a few things to note about the similarities and differences between small-program cloud development and Web cloud development:
@cloudbase/node-sdk
and if you want to use it on the small program side, you introduce
wx-server-sdk
@cloudbase/node-sdk is Cloud-developed service-side sdk, wx-server-s@cloudbase dk is a small program cloud development SDK;
未找到函数发布配置,是否使用默认配置(仅适用于 Node.js 云函数)
functions only).
Calling a cloud function on the web side is using the web side sdk, that is, the tcb-js-sdk module or the previous introduction of the tcb.js file, we can write the call of the function in the main.js file to the callback function of app.auth(), when the page loads when the anonymous user logs in, we can call the cloud function
window.onload= function(){
app.auth({
persistence: 'session' //在窗口关闭时清除身份验证状态
})
.anonymousAuthProvider()
.signIn()
.then(() => {
app.callFunction({
name: 'webtest',
data: { "name": "李东bbsky", "title": "杂役"}
})
.then((res) => {
console.log(res)
});
}).catch(err => {
console.log("登录失败",err)
})
Open (or refresh the page) using
http://localhost:5000/public/index.html
then you'll see the results of the local call to the cloud function in the browser developer tool console.
Let's do the following command to update the static page of the public to static storage, then open the
二级域名/web
and debug the code in the console of the browser developer tool:
cloudbase hosting:deploy ./public web -e xly-xrlur
By printing, we can see that the parameters uploaded on the web side are in the object, and the object returns the user's user's userInfo, which contains WeChat appId, while the context object contains some information about the cloud function.
With the web-side SDK, we can call cloud functions in the cloud development environment, and cloud functions can also call cloud functions, you can add and remove databases, cloud storage, but also use cloud calls (requires the exception of openid cloud functions), so we can also follow the use of cloud functions developed by small program clouds. We should also note that the cloud function is triggered using the CLoudbase Cli, and that the information about the cloud function that is triggered on the web side and the cloud function that is later obtained using cloud access will be different.
Like small program trigger event handlers, we can use event handlers by using lifecycle functions through the page, or by clicking, such as binding event handlers on the labels of web pages to trigger event handlers, to perform a series of operations on cloud functions, databases, and cloud storage.
For example, we can enter the following code in the index.html and the label under the public
<body>
in a button tag, binding the getData() event handler,
<button onclick="getData()">点击获取数据</button>
Then add the getData() event handler in the main .js, save the page, click the button to trigger the event handler, make a request for data, and here's a collection of chinas previously created in small program cloud development:
function getData(){
const db = app.database();
const _ = db.command
const $ = db.command.aggregate
db.collection("china")
.where({
gdp: _.gt(3000)
})
.field({
_id:false,
city: true,
province: true,
gdp:true
})
.orderBy('gdp', 'desc')
.skip(0)
.limit(10)
.get()
.then(res => {
console.log(res.data)
})
.catch(err => {
console.error(err)
})
}
Whether it is querying data, adding records to the database, deleting data, as well as instructions, aggregations, etc. have maintained a strong consistency with the development of small programs cloud, note that oh, real-time push of the database is also the same as the use of small programs.
It's worth noting that when anonymous users add data to the database, the cloud database also generates _openid fields by default, which is temporary and has been said before.
As with small program cloud development, in order to upload files on the front end, first we need to build a label to upload files, in the public folder under the index.html and then enter the following code, we only allow the upload of pictures, and binding
<input type="file" id="file" accept="image/*" onchange="uploadFile()">
Then we continue to enter .js code in the main code. T he selected file is returned with the HTMLInputElement.files property, which is a FileList object that contains a column of File objects. FileList behaves like an array, so you can check the length property to get the number of selected files.
function uploadFile() {
const filetemp = document.getElementById("file").files[0]
console.log("file对象",filetemp) //打印文件对象
const fileName = filetemp.name //从打印对象知道,这就是文件的名称
app.uploadFile({
filePath: filetemp, //本地文件
cloudPath: `tcb/${fileName}`, //云存储的路径
onUploadProgress: (progressEvent) => { //上传进度回调
let percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
console.log('上传进度: ' + percentCompleted, progressEvent);
}
}, function (err, res) {
console.log({err,res})
});
}
Note that this cloud storage path should not be preceded
/
nor directly root, otherwise there will be no upload permissions;
Enter the following code in the .html under the public folder, and we write a button that binds the deleteFile event:
<button onclick="deleteFile()">删除文件</button>
Then we continue to .js the deleteFile event handler in the main message and delete the fileID specified in the cloud store when we click the button:
async function deleteFile() {
const result = await app.deleteFile({
fileList: ['cloud://xly-xrlur.786c-xly-xrlur-1300446086/tcb/[email protected]']
})
result.fileList.forEach(item => {
if (item.code === 'SUCCESS') {
alert("文件删除成功")
}
})
}
Cloud development login also supports custom login, WeChat public platform, WeChat open platform login, which will be introduced later.