微信小程序通过云函数访问非https接口

需要用到一个插件request-promise
https://www.npmjs.com/package/request-promise
安装在云函数目录下
npm install --save request
npm install --save request-promise

安装request-promise环境了:
打开微信开发者工具,在小程序项目的云函数环境文件处右键单击,新建Node.js云函数,输入云函数名,回车;然后在刚才新建的云函数文件夹上右键,选择最下面的在终端打开,复制上面的安装命令(npm install --save request)到终端,回车,等待request安装。

image.png

这样request就安装完成了,然后再复制命令(npm install --save request-promise)到终端,安装 request-promise。
image.png

到这就安装完了,一定要先安装 equest,然后再安装request-promise。
这时打开云函数里的package.json文件,里面就会有对应的版本。
image.png

那么我们如何使用request-promise去发送请求呢:
在对应的云函数中进行
image.png

post

const rp = require('request-promise');
let options = {
    method:'POST',
    uri:'http://XXX/xxx/xxx',
    body:{
      "uid": ''
    },
    json:true
  };
  let result = await rp(options).then(res=>{
    return res;
  }).catch(err=>{
    console.error(err);
  })

get

rp('http://XXX/xxx/xxx')
    .then(function (htmlString) {
        // Process html...
    })
    .catch(function (err) {
        // Crawling failed...
    });

编辑完云函数一定要上传并部署,之后在我们小程序的对应页面的.js文件里调用云函数使用

wx.cloud.callFunction({
    name:'云函数名',
    // 这里根据实际添加其他条件
}).then(res =>{
   console.log("请求成功:"+JSON.stringify(res));
   //处理请求成功后的数据逻辑
}).catch(err => {
   console.error("请求失败:"+err);
})

你可能感兴趣的:(微信小程序通过云函数访问非https接口)