got and request promise in cloud development

Today, learn how cloud development makes requests and conducts data security monitoring

Problem: it is OK to request token with got, but an error is reported during security monitoring

I found a lot of articles on the Internet, and also communicated with others in the group. After a comprehensive review, I found a solution ------ use request promise instead of got

I use got when I get the token, and request promise when I carry out security detection. Yes, I use two packages to complete this function at the same time (after all, in the learning process, it's different from wechat that doesn't support template messages, because I can't get the formId, so I can't learn it ()

Request promise usage reference
Wechat content security detection document

Here is the code:

js on the applet side

Page({

  msgCheck:function(event){
    wx.cloud.callFunction({
      name:'msg',
      data:{
        text:'2347 complete dfji 3726 tests asad Sense 3847 knowledge qwez reach'
        // text: 'hello'
      }
    }).then(res => {
      console.log(res)
      console.log(res.result)
      // console.log(JSON.parse(res.result))
    })
  }
})

js code in the cloud

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

const got = require('got')

const rp = require('request-promise')


let appid = 'Your appid;
let screct = 'Your screct';
let msgCheckUrl = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token='

let tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+appid+'&secret='+screct


cloud.init()



// Cloud function entry function
exports.main = async (event, context) => {
  let tokenResponse = await got(tokenUrl)
  // console.log(tokenResponse.body)
  let token = JSON.parse(tokenResponse.body).access_token;
  console.log(token)
  var options = {
    method: 'POST',
    url: "https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+token,
    body: {
        content: event.text
    },
    json: true // Automatically stringifies the body to JSON
};

//The following is the code of got error A kind of
// a = rp(options)
//     .then(function (parsedBody) {
//       // console.log(parsedBody)
//       //   return parsedBody
//     })
//     .catch(function (err) {
//         // POST failed...
//     });
return await rp(options)
  // let checkResponse = await got(msgCheckUrl + token,{ 
  //   method:'POST',
  //   headers:{
  //     'Content-Type':'application/json'
  //   },
  //   body:JSON.stringify({
  //     content:event.text
  //   })
  // });
  // return options.body
  // return token;
}

Conclusion: To study why an error is reported, it is better to find another way to solve it. The former seems to waste more time

Tags: Javascript JSON SDK

Posted on Wed, 18 Mar 2020 11:33:12 -0400 by OU_Student