小程序 | 云函数 |
---|---|
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 }) } })