微信小程序云开发(云函数)学习笔记01-发送http请求

为什么使用云函数发送http请求?

1、不受5个可信域名限制 ,另外一个意思就是可以不是可信域名

2、所请求的域名可以不备案

为什么要使用云函数发送http请求?1、不受5个可信域名限制,2、可以不备案(也不可以不用https)

注: 以上规则在笔者学习的时候还是有效的!

 想要在云函数中发送http请求,要借助外部的packge来完成,笔者所学的教程中介绍的是 got

测试代码如下:

添加了名为http的pages

miniprogram:pages/http/http.wxml

 1 <button bindtap="http">http</button> 

miniprogram:pages/http/http.js

复制代码

 1 Page({
 2     http:function(e){
 3       wx.cloud.callFunction({ //调用云函数
 4         name:'http'           //云函数名为http
 5       }).then(res=>{      //Promise
 6         console.log(JSON.parse(res.result))
 7       })
 8     },
 9 
10 })

复制代码

 新建名为http的云函数并在http云函数目录下安装got

npm install --save got

编辑http.js

cloudfunctions:http/http.js

复制代码

 1 // 云函数入口文件
 2 const cloud = require('wx-server-sdk')
 3 
 4 const got = require('got'); //引用 got
 5 
 6 cloud.init()
 7 
 8 // 云函数入口函数
 9 exports.main = async(event, context) => {
10   //let getResponse = await got('httpbin.org/get') //get请求 用httpbin.org这个网址做测试 
11   //return getResponse.body
12   let postResponse = await got('httpbin.org/post', { 
13     method: 'POST', //post请求
14     headers: {
15       'Content-Type': 'application/json' 
16     },
17     body: JSON.stringify({ //把json数据(对象)解析成字符串
18       title: "网址",
19       value: 'anipc.com'
20     })
21   })
22 
23   return postResponse.body //返回数据
24 }

复制代码

 这里只测试了get和POST两种请求方式,其他请参照got文档 

保存后 上传并部署

需要说明的是:现在云函数本地不需要安装依赖了,可以云安装依赖,也就是说你在新建云函数是没有安装wx.server.sdk的,如果点 上传并部署:所有文件  的话,就要先在本地先安装本地依赖。

npm install --save wx-server-sdk

测试一下:

get

post

猜你喜欢

转载自blog.csdn.net/qq_36935391/article/details/89391488