Why send http requests using cloud functions?
1, from 5 credible domain name restrictions, other means that may not be credible domain name
2, the requested domain name can not record
Note: The above rule when I learned is still valid!
Want to send http request in the cloud function, must rely on external packge to complete the tutorial I have learned in this article is got
Test code is as follows:
Add the pages of named http
miniprogram:pages/http/http.wxml
<button bindtap="http">http</button
miniprogram:pages/http/http.js
. 1 Page ({ 2 HTTP: function (E) { . 3 wx.cloud.callFunction ({ // call the function cloud . 4 name: 'HTTP' // cloud function called HTTP . 5 .}) The then (RES => { // Promise . 6 the console.log (the JSON.parse (res.result)) . 7 }) . 8 }, . 9 10 })
New function named http cloud and cloud function installed in the directory http got
npm install --save got
Edit http.js
cloudfunctions:http/http.js
1 // cloud function entry file 2 const = Cloud the require ( 'WX-Server-SDK' ) . 3 . 4 const = GOT the require ( 'GOT'); // reference GOT . 5 . 6 cloud.init () . 7 . 8 // cloud function entry function . 9 exports.main the async = (Event, context) => { 10 // the let getResponse the await GOT = ( 'httpbin.org/get') // do the GET request URL test httpbin.org . 11 // return getResponse .body 12 is the let postResponse the await GOT = ( 'httpbin.org/post' , { 13 is Method: 'the POST', // POST request 14 headers: { 15 'the Type-the Content': 'file application / json' 16 }, . 17 body: the JSON.stringify ({ // the json data (objects) to parse the string 18 is title: "URL" , . 19 value: 'anipc.com' 20 is }) 21 is }) 22 is 23 is return postResponse.body // return data 24 }
Here only we get tested and POST request methods, please refer to the other got the document
After uploading and saving deployment
It should be noted: the cloud now need to install depend on the local function, you can install the cloud-dependent, which means you are not installed in the new cloud wx.server.sdk function, if the point of upload and deploy: all the files, then we would first locally installed locally dependent.
npm install --save wx-server-sdk
have a test:
get
post