小程序雲開發請求第三方http或https接口


1.新建http雲函數,選中http雲函數,右鍵,打開終端,安裝依賴:
npm install request-promise
2.http.js引入request-promise用於做網絡請求
var rp = require('request-promise');
3.雲函數入口函數邏輯
  // 雲函數入口函數
  exports.main = async (event, context) => {
  console.log(event,context)
  let url = event.url;
  if (event.method == "post" || event.method == "POST" || event.method == "Post") {
    //發送post請求
  } else {
    //發送get請求
  }
 }
4.http.js中get請求
var options = {
      uri: url,
      method:"GET",
      qs: event.datas,
      headers: {
          'User-Agent': 'Request-Promise'
      },
      json: true 
  };
  rp(options)
      .then(function (res) {
        return res
      })
      .catch(function (err) {
       return '失敗'
      });
5.http.js中post請求
   var options = {
      method: 'POST',
      uri: url,
      body: {
          some: 'payload'
      },
      form: event.datas,
      json: true 
  };
  rp(options)
      .then(function (res) {
        return res
      })
      .catch(function (err) {
        return '失敗'
      });
6.選中http雲函數,右鍵,上傳並部署:雲端安裝依賴
7.雲端測試
8.調用:
      wx.cloud.callFunction({
      // 要調用的雲函數名稱
      name: 'http',
      // 傳遞給雲函數的event參數
      data: {
        url:"http://api.xxx.com/api/xxx",
        method:"get",
        datas:{
          msg:"xxx"
        }
      }
    }).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM