今天學習雲開發如何發請求和進行數據安全監測
問題:用got請求token可以,但進行安全監測時卻報錯
在網上找了許多篇文章,也在群里跟別人交流過,綜合了一下,找到了解決辦法------用request-promise代替got
我這是獲取taken時用got,進行安全檢測則使用request-promise,沒錯同時用了兩包來完成這個功能(畢竟是學習過程中,這可和微信不支持模板消息不一樣,因為已經獲取不了formId,實在是學不了了😂)
request-promise使用參考
微信內容安全檢測文檔
下面展示代碼:
小程序端的js
Page({
msgCheck:function(event){
wx.cloud.callFunction({
name:'msg',
data:{
text:'完2347全dfji試3726測asad感3847知qwez到'
// text:'你好呀'
}
}).then(res => {
console.log(res)
console.log(res.result)
// console.log(JSON.parse(res.result))
})
}
})
雲端的js代碼
// 雲函數入口文件
const cloud = require('wx-server-sdk')
const got = require('got')
const rp = require('request-promise')
let appid = '你的appid;
let screct = '你的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()
// 雲函數入口函數
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
};
//下面是got報錯的代碼😂
// 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;
}
總結:去研究為什么報錯,不如換一種方法去解決,前者似乎更浪費時間
