The adaptation of uni app to the cloud function of wechat applet

Introduction

People who are familiar with uni app should know that uni app does not adapt the cloud function of wechat applet (collectively referred to as cloud function in this article). But what if we need to use cloud functions in some business scenarios? We know that cloud functions can be copied to wechat developers' tools, so we have to copy them manually every time we compile them, which is extremely troublesome. This paper makes the following solutions to the problems.

Article environment

  1. Hbuilder X
  2. Wechat developer tools

Create cloud function directory

First of all, we need to create a cloud function directory under the uni app project folder. The path is arbitrary. Here are functions. Then, you can put some files in it. Here, take new file.css as an example.

Modify manifest.json
In the root directory of uni app, modify the wechat applet item in manifest.json. The structure is as follows

"mp-weixin" : {
        /* Applet specific correlation */
        "appid" : "wxd7de467f6e6cf741",
        "cloudfunctionRoot": "./functions/", // This line is the field to mark the cloud function directory
        "setting" : {
            "urlCheck" : false
        },
        "usingComponents" : true
    }

Write vue.config.js

  1. We create the vue.config.js file in the root directory of the project
  2. Write the following contents (if the path is different, please make corresponding adaptation)
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')

module.exports = {
    configureWebpack: {
        plugins: [
            new CopyWebpackPlugin([
                {
                    from: path.join(__dirname, 'functions'),
                    to: path.join(__dirname, 'unpackage/dist', process.env.NODE_ENV === 'production' ? 'build' : 'dev', process.env.UNI_PLATFORM, 'functions')
                }
            ])
        ]
    }
}
  1. Compile and run
    Find the following

Note: the copy webpack plugin plug-in is not installed. Let's install it manually.

Then compile and run, and find the following contents in wechat developer tools.

Up to now, the automatic copying from Hbuilder X to wechat developer tools has been completed, that is, the core content of this article has been solved. The following are further tests.

Create cloud functions

We right-click the root directory of the cloud function. In the right-click menu, you can choose to create a new Node.js cloud function. We name the cloud function
 It's check. The developer tool creates the cloud function directory and the entry index.js file locally, and creates the corresponding cloud function in the online environment
 Number. After the creation is successful, the tool will prompt whether to install the dependency locally immediately. After confirmation, the tool will install the Wx server SDK automatically. We will see
 The following.

After creation, it can be synchronized and copied to the uni app project, which is convenient for automatic line synchronization in the future, and can avoid the accidental loss of cloud functions in the output folder. So far, the preparation of relevant documents has been transferred to Hbuilder X, and the upload and deployment of cloud functions are still in wechat developer tools.

Write cloud functions

The default cloud function is just a content that returns the basic data of users. We modify it to meet our business needs. Take the content security cloud call as an example.

Write the following in the cloud function file

// Cloud function entry file
const cloud = require('wx-server-sdk')

cloud.init()

// Cloud function entry function
exports.main = async(event, context) => {
  try {
    console.log('Text to be tested:' + event.content);
    let result = await cloud.openapi.security.msgSecCheck({
      content: event.content
    })
    console.log('result:' + JSON.stringify(result));

    if (result && result.errCode.toString() === '87014') {
      return {
        code: 300,
        msg: 'Content contains illegal content',
        data: result
      }
    } else {
      return {
        code: 200,
        msg: 'ok',
        data: result
      }
    }

  } catch (err) {
    if (err.errCode.toString() === '87014') {
      return {
        code: 300,
        msg: 'Content contains illegal content',
        data: err
      }
    }
    return {
      code: 400,
      msg: 'call security Interface exception',
      data: err
    }
  }
}

Declaration of competence

In the function directory, create a config.json. The document says that it will be created automatically, but I didn't create it automatically in actual operation. The content of config.json is as follows.

{
    "permissions": {
        "openapi": [
            "security.msgSecCheck"
        ]
    }
}

Then right click in the function directory, upload and deploy.

Applets call cloud functions

wx.cloud.init()
                wx.cloud.callFunction({
                    name: 'check',
                    data: {
                        "content": this.contents.join()
                    }
                }).then(res => {
                    console.log(res.result)
                    if (res.result.code == 300) {
                        uni.showModal({
                            title: "Reminder",
                            content: "The content you entered may contain illegal content, and the next step is not supported"
                        })
                        return
                    } else {
                        ... // What do you want to do
                    }
                })

Effect display

Reprinted from: https://www.jianshu.com/p/fc5f88721439

29 original articles published, 40 praised, 5477 visited
Private letter follow

Keywords: JSON Vue Webpack SDK

Added by toffler on Sun, 23 Feb 2020 05:15:18 +0200