微信小程序如何發送 http 請求

  • 爲何要使用雲函數發送 http 請求
小程序 雲函數
5 個可信域名 不受限制
須要備案 無需備案

在一些特殊情境, 好比域名沒有備案或域名 5 個以上就須要使用雲函數發送 HTTP 請求了.npm

  • 如何使用雲函數發送 HTTP 請求? 在雲函數中可以使用各類 Package 來發送 HTTP 請求, 在這演示 got.
  1. npm 安裝 got 庫

npm install gotjson

  1. 安裝完成後能在 package.json 中看到新增了 got 依賴小程序

  2. 經過 `httpbin.org' 來測試 HTTP 請求app

  • get 請求方式
// 雲函數入口文件
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
}
  • post 請求方式
// 雲函數入口文件
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 文件
<!--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
    })
  }
})
相關文章
相關標籤/搜索