14
头图

Uniapp cloud function tutorial login article

Today we use uniapp provided cloud functions and cloud database to achieve a simple login, registered function.
Before following this tutorial, you need to understand briefly:

Of course, no, it doesn't matter, I will elaborate slowly.

1. Getting started

Let’s first briefly introduce the prerequisites needed to implement a login and registration function.

  • A front-end template
  • database
  • Backend code

Front-end template

If you don't know the front end, we can find a template. As used herein, the template for the amo***@qq.com provide plug- minimalist Login Register template

database

We will use the conventional development mysql to develop, and today we use uniapp provided document database JSON format, by definition, it is a JSON-formatted document for each record in the database.

I will not elaborate on them here. For details, please refer to Basic Concepts of Cloud Database

Backend code

Here we use uniapp . The cloud function is the JavaScript running in the cloud, which is the Node.js development. Developers familiar with Node.js can get started directly.

2. Preparation

3. Front-end project

3.1 Import front-end template

Open the plugin library minimalist login registration template , click use HBuilderX to import the plugin, as shown in the following figure 3.1

Figure 3.1
image.png

After that, the editor will be opened to import, remember to check enable uniCloud, as shown in the following figure 3.2

Figure 3.2
image.png

After the import is successful, you will get the following directory

image.png
In this way, the front-end template is created, and then we first write the front-end logic

3.2 Modify the front-end code

3.2.1 Delete other registered codes of
image.png
The method of writing the login request interface (the complete code can be viewed in the demo code)

uni.showLoading({
    title: '登录中'
});
uni.request({
    url: 'xxxxxxxxxxx',
    data: {
        phoneData: this.phoneData,
        passData: this.passData
    },
    success: (res) => {
        console.log('res', res)
        // uni.showToast({
        //     icon: 'error',
        //     position: 'bottom',
        //     title: '账号或密码错误,账号admin密码admin'
        // });
    },
    complete: () => {
        uni.hideLoading();
        this.isRotate=false
    }
})

3.2.2 Registration is changed to only need account and password to register
image.png
Write the registration code (the complete code can be viewed in the demo code)

_this.isRotate = true
uni.showLoading({
    title: '注册中'
});
uni.request({
    url: 'xxxxxxxxxxx',
    data: {
        phoneData: this.phoneData,
        passData: this.passData
    },
    success: (res) => {
        console.log('res', res)
    },
    complete: () => {
        uni.hideLoading();
        _this.isRotate = false
    }
})

4. Associated cloud functions

Right-click the UniCloud folder and click associate a cloud service space or project
image.png
Click New, ( real-name authentication required in advance)
image.png
Next will be redirected to the web page, we choose Cloud
image.png
After the creation is complete, return to the editor and click refresh, select the newly created service space, and click associate
image.png

4.1 add cloud database

Adding a cloud database can either add code or use the web page for operation, here we use the web page for operation
Open the unicloud service space list , enter the newly created service space, and choose to create a new cloud function library.
image.png
Just create an empty table, no need to select a template
image.png
Modify the table structure as follows
image.png

{
  "bsonType": "object",
  "required": [],
  "permission": {
    "read": false,
    "create": false,
    "update": false,
    "delete": false
  },
  "properties": {
    "_id": {
      "description": "ID,系统自动生成"
    },
    "phoneData": {
      "description": "用户名"
    },
    "passData": {
      "description": "密码"
    }
  }
}

At this point, the database has been created. Next, we create a new cloud function that handles the interface

4.2 New Cloud Function

4.2.1 Registration function

  • Right-click the cloudfunctions folder, click create a new cloud function

image.png
image.png
Write the registration code, here we only do the data insertion operation, do not consider the de-duplication here, you can optimize it yourself
image.png

'use strict';
exports.main = async (event, context) => {
    //event为客户端上传的参数
    console.log('event : ', event)

    const db = uniCloud.database(); //代码块为cdb
    const collection = db.collection('userTable');

    let queryStringParameters = event.queryStringParameters
    let res = await collection.add({
        phoneData: queryStringParameters['phoneData'],
        passData: queryStringParameters['passData']
    })
    //返回数据给客户端
    return {
        mesg: '注册成功',
        code: 200
    }
};
  • Right-click cloudfunctions and select upload all cloud functions··

image.png

  • Enable domain name binding

image.png
Just open
image.png

  • Select the registration function just now, click on the details

image.png

  • /http/register , click to edit, fill in 0616fd6e916789

image.png

This url is our registration interface

4.2.1 Login function

In the same way, create a new login and fill in the logic code
image.png

'use strict';
exports.main = async (event, context) => {
    //event为客户端上传的参数
    console.log('event : ', event)
    const db = uniCloud.database(); //代码块为cdb
    const dbCmd = db.command
    const $ = dbCmd.aggregate
    let callback = {}

    let queryStringParameters = event.queryStringParameters
    let phoneData = queryStringParameters['phoneData']
    let passData = queryStringParameters['passData']

    const collection = db.collection('userTable');
    let res = await collection.where({
            phoneData: dbCmd.eq(phoneData)
        })
        .get()
    console.log('res.data[0].passData : ', res.data[0].passData)
    console.log('passData : ', passData)
    if (res.data.length == 0) {
        callback = {
            mesg: '没有此账号',
            code: 500
        }
    } else {
        if (res.data[0].passData == passData) {
            callback = {
                mesg: '登录成功',
                code: 200
            }
        }

        if (res.data[0].passData !== passData) {
            callback = {
                mesg: '密码错误',
                code: 500
            }
        }
    }

    //返回数据给客户端
    return callback
};

Fill in the list of services /http/login
image.png
Then we fill in the login and registration interface just now into the spare front-end code before

5. Front and back joint debugging (apis are currently all get requests!)

5.1 Registration

image.png

5.2 Login

image.png

image.png

image.png

summary

Today’s login chapter ends here.
The place to be optimized for the demo is repeated registration. There is no optimization here, and you can optimize it yourself.

demo source code download
demo source code download gitee

Next: uniapp cloud function tutorial ②:

WX20210922-091703.png


雾岛听风
12.1k 声望8.6k 粉丝

丰富自己,胜过取悦别人。