微信小程序如何发送 http 请求

  • 为什么要使用云函数发送 http 请求
小程序 云函数
5 个可信域名 不受限制
需要备案 无需备案

在一些特殊情境, 比如域名没有备案或域名 5 个以上就需要使用云函数发送 HTTP 请求了.

  • 如何使用云函数发送 HTTP 请求?
    在云函数中能够使用各种 Package 来发送 HTTP 请求, 在这演示 got.
  1. npm 安装 got 库

npm install got

  1. 安装完成后能在 package.json 中看到新增了 got 依赖

  2. 通过 `httpbin.org' 来测试 HTTP 请求

  • 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.js

Page({
  http: function(event) {
    wx.cloud.callFunction({
      name: 'http'
    }).then( res => {
      console.log(res.result) // get
      console.log(JSON.parse(res.result)) // post
    })
  }
})

你可能感兴趣的:(微信小程序如何发送 http 请求)