利用云函数绕过域名校验和HTTPS配置,实现内网加端口访问
闲来无事,无意中发现云函数中的request网络请求可以不用配置校验域名和https,也就是说可以通过云函数封装一个请求通用函数来处理没有域名和https的网络请求(甚至包括内网穿透,可以用非80端口进行实验)。
适用场景:
A、没有域名或使用局域网(直接使用IP访问);
B、使用花生壳动态域名解析(内网穿透);
C、有域名但不想申请配置HTTPS(懒人);
D、连自己的服务器都没有,接口直接使用开源或者第三方接口且不能添加域名校验的情况(空壳);
E、不愿意直接在小程序中直接暴露自己逻辑API实际请求地址的(安全);
······
具体步骤如下:
1、给项目添加云函数支持(https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/getting-started.html)
2、新建名为“proxy”的云函数,配置支持request-promise
// package.json{ "name": "proxy", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "wx-server-sdk": "latest", "request": "latest", "request-promise": "latest" }} |
const cloud = require('wx-server-sdk')const rq = require('request-promise')cloud.init()// 云函数入口函数// event为小程序调用的时候传递参数,包含请求参数uri、headers、bodyexports.main = async (event, context) => { return await rq({ method: 'POST', uri: event.uri, headers: event.headers ? event.headers : {}, body: event.body }).then(body => { return body }).catch(err => { return err })} |
3、在小程序中调用云函数请求数据请求
onLoad: function(){ // 初始化 wx.cloud.init()},onGetItemList: function(){ wx.cloud.callFunction({ name: 'proxy', data: { // http域名 https域名 第三方域名 非验证域名 IP[:prot] 内网IP或花生壳域名 uri: 'http://192.168.1.100:8081', headers: { 'Content-Type': 'application/json' }, body: { uid: 1 } } }).then(res => { console.log(res) const data = res.result console.log(data) // do something })} |
然后你会发现你已经无所不能了。
个人见解,如有不妥之处,望各位大神指正!~
