Belong to your micro channel small program background management system!! (Only refers to cloud development of small programs oh. 😁) if you have already made a cloud development of wechat small program, but have not given it with a background management system, then act quickly!! This article will walk you through the implementation in detail, including some bug fixes in the process (which may not be bugs to the boss ðŸĪĢ).


preface

This article contains 3920 words and takes 15 minutes to read. Like first, then look, make a habit! Creation is not easy, thank you for your support! âœĻ âœĻ

Please take some time to quietly read this article, believe me, you will be able to achieve their own small program background management system. (for those who need it 😊😊😊)

This article is mainly based on the open source project VUE-Admin-Template + KOA + Element-UI + wechat cloud development HTTP API to achieve a wechat applet background management system. Using the front and back end separation architecture, vue-admin-Template to achieve the front end of the management system interface, we use Koa2 here to achieve the back end, of course, you can also change to other frameworks to achieve.

Let’s take a look at a wave of renderings






Here are the implementation steps

First, front-end project initialization

Clone the original foreground project from Github with the project address

  • 1. After success, open the project with the vscode editor

  • 2, We left only login folder and 404.vue in the views directory, delete all the others. Then according to their own small program needs to manage the data design needs what front page, according to their own needs to build a good project view file.

  • 3, next, in the router folder index.js according to the design of the page route planning (about the route configuration will not be detailed)

  • 4. Decide how the data will be displayed and what operations will be required. (Because this template already integrates element-UI, the project in this article is relatively simple, so only use table, button, dialog and form components.)

  • 5. As the last step, we will wrap a.js file for each front-end page in the API folder SRC, write the method of retrieving back-end data in it, and then introduce the method of retrieving back-end data in the view page in the Views folder.


Here I use this project directory and clone project directory to compare it should be a little clearer.

The following figure shows the initial cloned project file directory. Note the marked areas in the figure.

The following figure shows the file directory of this project. Notice where the notes are and you’ll notice only two changes.

  • 1, I was inviewsThree folders have been created under the directoryplaylist,swiper,blog, respectively represent the abovegifThe view file of song list management, rotation chart management and blog management page shown in the figure. (Of course, you’ll have to tailor it to your own mini-program.)
  • 2, inapiThree new files are created under the directoryplaylist.js,swiper.js,blog.js, respectively for the data acquisition of the three pages in the previous point.


  • At this point, the front-end project initialization is complete. ðŸ’Ķ ðŸ’Ķ
  • Next, we initialize the back-end project.

2. Backend project initialization

  • 1. Initialize a Node project and install project-related dependencies. This project uses only the following dependency package KOA — the backend framework koA-Router used in this project — the route management tool KOA-body — the NPM package for post request parameter resolution KOA2-CORS — the NPM package for front and back end cross-domain problems Request, request-promise – used to send requests for data in the applets cloud database

  • 2. Create an app.js file in the root directory for the entry file of the back-end service

  • Create a new controllers folder in the root directory to hold the JS files that fetch data from the cloud database

  • 4. Create a new utils folder in the root directory to store some utility files


  • At this point, the backend project initialization is complete. ðŸ’Ķ ðŸ’Ķ
  • Next, we carried out the docking of the front and back end projects.

Iii. Docking of front and back end projects

Here I put this project in a page data acquisition of the complete process to go again, easy to understand. Take the first page, the singleton list, for example. Get started!!

Front end:

  • In the front end projectviewsIn folderplaylist.vueThe deconstructedapiIn folderplaylist.jsMethod encapsulated in. As shown in the figure:

The fetchList method is used to get playlists and the del method is used to delete playlists. The code isn’t that long, so I’m going to post these two methods directly from playlist.js. As follows :(baseURL is the address opened by the back-end project, and the request method is the axios request method wrapped by the template project)

import request from '@/utils/request'
const baseURL = 'http://localhost:8888'

export function fetchList(params) {
    return request({
        params,
        url: `${baseURL}/playlist/list`,
        method: 'get'})}export function del(params) {
    return request({
        params,
        url: `${baseURL}/playlist/del`,
        method: 'get'})},Copy the code

The backend:

  • 1. With the front-end request method written, it’s time to move on to the back-end project. Let’s start with the entry file for our back-end projectapp.jsIn the.

The code is as follows (the code is explained above) :

const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router'Const router = new router () const cors = require('koa2-cors'Const koaBody = require(const koaBody = require('koa-body') // Corresponding to your own applets cloud environment id const ENV ='jingjing-haohao'// Cross-domain app.use(cors({// front-end project request address. origin: ['http://localhost:9528'],
    credentials: true})) app.use(koaBody({multipart:true
}))

app.use(async(ctx, next) => {
    console.log('Jingjing global middleware') // Configure global variables. Ctx.state. env = env await next()}) const playlist = require(ctx.state.env = env await next()})'./controllers/playlist')
router.use('/playlist', playlist.routes()) app. Use (router.routes()) app. Use (router.allowedmethods ()) () => { console.log('Project started on port 8888,,,')})Copy the code
  • 2. Register in the project entry fileplaylistAfter routing, we now come tocontrollersUnder folderplaylist.jsIn the.

Here’s the code :(to avoid getting too long, I’ve only posted the code for removing the feature.) All code click here playlist.js

const Router = require('koa-router')
const router = new Router()
const callCloudDB = require('.. /utils/callCloudDB')
router.get('/del', async(ctx, next) => {
    const params = ctx.request.query
    const query = `db.collection('playlist').doc('${params.id}').remove()`
    const res = await callCloudDB(ctx, 'databasedelete', query)
    ctx.body = {
        code: 20000,
        data: res
    }
})
module.exports = router
Copy the code

Some explanations are as follows:

  • 1. For heregetorpostThe method must be the same as the front-end request method.
  • 2,queryIs to operate the databasesqlStatements.
  • 3. Return to the backend datacode=20000, which is the status code specified in the front end template that the back end must return before the request is considered successful.
  • 4. The third line of code is importedcallCloudDBModule, this is because when we request or query the cloud database and operate the cloud database, we check the official documents of wechat and find that the request address given is very similar (only one parameter in the address is different) and the request parameters are exactly the same. So we encapsulate it into onecallCloudDBThe module. Later, when you need to interact with the database, you simply call this method and pass in the corresponding parameters. Such as the abovedelMethod requires the code to delete database dataconst res = await callCloudDB(ctx, 'databasedelete', query), includingctxIs the context,databasedeleteFixed parameters for the delete operation,queryforsqlStatements. And then you need to do something else as long as you change the parameters. How about, is it very convenient 😎😎😎?

Callclouddb.js code attached:

const getAccessToken = require('./getAccessToken.js')
const rp = require('request-promise')

const callCloudDB = async(ctx, fnName, query = {}) => {
    const ACCESS_TOKEN = await getAccessToken()
    const options = {
        method: 'POST',
        uri: `https://api.weixin.qq.com/tcb/${fnName}? access_token=${ACCESS_TOKEN}`,
        body: {
            query,
            env: ctx.state.env,
        },
        json: true // Automatically stringifies the body to JSON
    }

    return await rp(options)
        .then((res) => {
            return res
        })
        .catch(function (err) {
            console.log(err);
        })
}

module.exports = callCloudDB
Copy the code

Some explanations are as follows:

  • ACCESS_TOKENCall credentials for the applet interface, and parameters necessary for applet data interaction, introducedgetAccessToken.jsTo get it,getAccessToken.jsMore on that later. aboutAccessToken, the official documentation has detailed explanationLink here!

Let’s simply go over the idea again from the beginning.

  • 1. The front end is inapiWrite the request method to obtain data in the file, and the parameters to be used for back-end transmission.
  • 2. We’re at the back endcontrollersCreate corresponding files under the folder, as shown in the figure:

  • 3. Write the code of operating your own cloud function or cloud database with the help of the method provided by the HTTP API document under cloud development in the official wechat document. Return the value to the front end with a status code (20000)
  • 4. Write pages in the front-end project (the initial project is already integratedelement-uiWe can use it directly), do some processing on the data returned from the back end, and then display it on the page.

That’s about it, and the rest of the page goes exactly the same way. There are some details that I’m going to talk about, some details that I’m not going to talk about. Maybe my writing is not good enough to understand, or maybe my friends did not understand too much, welcome to discuss in the comment section. Need can contact the author to discuss together oh. 😁


4. What I feel better about the project (Baymax feeling 🙄🙄🙄)

1. The utility files encapsulated on the back end are nice (i.e. files in the utils folder)

  • Call credentials for the applet’s interfaceACCESS_TOKENThe fetch encapsulates agetAccessToken.jsFile, which is used to getACCESS_TOKENGenerate one in the sibling directoryaccess_token.jsontheJSONThe file,ACCESS_TOKENSave it in and save the time to get it. Then put thegetAccessTokenAs a module export, in other pages can be imported directly for use. And it’s in the fileACCESS_TOKENDo the expiration time judgment, expired on the acquisition (becauseACCESS_TOKENValid for 2 hours)
  • Encapsulates one for the operational cloud databasecallCloudDB.js, the function of this file has been mentioned above.
  • Encapsulates one for the operation cloud functioncallCloudFn.jsBecause the parameters required by the interface to operate the cloud function call are different from the parameters passed into the cloud function, they can be reused easily.

2. Front-end template projects are awesome, we just need to modify the view and routing in the template project according to our own needs.

  • Template project author (Worship) —Flower shorts
  • githubAddress –Github.com/PanJiaChen/…

V. Problems encountered during the completion of the project (of course, it does not mean that partners will have the same problems)

1. When the browser slides to the bottom of the page, it retrieves data from the database again and displays it on the page.

  • I was just about to make the following decision about whether the browser had slid to the bottom.

1, access to document the actual height of the article (that is, how much set every time you pick up the data on the page display the height) of const scrollHeight = document. The documentElement. ScrollHeight 2, obtain the visual height of the browser window is visible to the naked eye that part of the full screen height const clientHeight = document. The documentElement. 3, obtain the height of the browser scroll up const clientHeight scrollTop = document.documentElement.scrollTop

  • After taking these three data points, according toscrollHeight == scrollTop + clientHeightThis criterion controls whether the data is retrieved again, then,, and ðŸĪ•ðŸĪ•
  • Look at the picture

  • Finally I thought of this point, could it be that there is a problem. The three data were printed out separately as shown in the picture above. The red box is the data printed out by the browser at the bottom. I cried ðŸĪŠðŸĪŠ
  • We found thatScrollHeight ratio scrollTop + clientHeightThat’s 0.28, 0.28. So lead toscroll.jsIt didn’t work. This problem is solved by changing the judgment condition.

2. When I get the release date on the blog page

  • That’s the red box
  • I just started seeing it in the data back at the back endcreateTimeThere’s one down here$dateBut I just can’t get the value. Tried for a long time, and then I putcreateTimePrint it out and find it’s a{__ob__: Observer}. Then Baidu found a lot of such problems, according to the method of a netizen to solve smoothly. Need to return the datadataTo convertJSONString, and then convert from string toJSONFormat that isJSON.parse(JSON.stringify(data))(Although I know that to do so can solve the problem, but I do not know why 😅, I hope that if there is an understanding of the big guy to baymax explain. 😁)
  • Time formatting is adoptedmoment.jsTo solve it,moment.jsThis time processing class library is really convenient! It’s easy to use! I recommend it, with a link at the end. (Learned halfway through writing this article ðŸĪĢðŸĪĢ)

Write in the last


This article is the second one written by the author. Although it takes a lot of time, it still feels a bit sweaty to write such a big article. If there is a mistake in the text, please forgive me, pointing out the error is better, so that the new man more than a learning opportunity. 😊 😊

Hope to see the friends can move a thumbs up and then go oh, thank 🙏🙏. Your support is the biggest encouragement for me!! Attached is the project address, welcome students who need to take it.

  • Github address of this project – github.com/jingjing20/…

Reference documentation

  • My Moment. Js Chinese website
  • element-ui
  • Wechat cloud development HTTP API documents