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

2019-01-26  本文已影响0人  Gnahzi
小程序 云函数
5 个可信域名 不受限制
需要备案 无需备案

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

  1. npm 安装 got 库

npm install got

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

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

// 云函数入口文件
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
    })
  }
})
上一篇 下一篇

猜你喜欢

热点阅读