小程序 | 雲函數 |
---|---|
5 個可信域名 | 不受限制 |
須要備案 | 無需備案 |
在一些特殊情境, 好比域名沒有備案或域名 5 個以上就須要使用雲函數發送 HTTP 請求了.npm
npm install gotjson
安裝完成後能在 package.json 中看到新增了 got 依賴小程序
經過 `httpbin.org' 來測試 HTTP 請求app
// 雲函數入口文件 const cloud = require('wx-server-sdk') const got = require('got'); cloud.init() // 雲函數入口函數 exports.main = async (event, context) => { let getResponse = await got('httpbin.org/get') return getResponse.body }
// 雲函數入口文件 const cloud = require('wx-server-sdk') const got = require('got'); cloud.init() // 雲函數入口函數 exports.main = async (event, context) => { let postResponse = await got('httpbin.org/post', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body:JSON.stringify({ title: 'title test', value: 'value test' }) }) return postResponse.body }
<!--pages/http/http.wxml--> <button bindtap='http'>http</button>
// pages/http/http.js Page({ http: function(event) { wx.cloud.callFunction({ name: 'http' }).then( res => { console.log(res.result) // get console.log(JSON.parse(res.result)) // post }) } })