前端技术栈:微信小程序使用got发送HTTP请求(封装模板)

在微信小程序发送 HTTP 请求的时候,会遇到这样一种情况——微信官方要求服务端口必须是过审的 HTTPS 请求。但是作为个人学习开发,申请一个 HTTPS 的端口成本太高,本篇就介绍一种使用微信小程序免费的云函数功能跳过 HTTPS 端口检验的方式。


云函数

1. 创建云函数

首先在微信小程序中申请云开发,创建一个名为http的云函数。创建成功后入下图所示。
http云函数

2. 安装依赖包

在云函数文件夹使用 npm 安装依赖包,本模板需要安装两个依赖包,分别为got包和form-data包。

这里需要注意的是got包最新版本(10.0.0)不支持微信小程序云开发,需要安装9.6.0版本。

npm install got@9.6.0 --save
npm install form-data --save
3. 云函数模板
// 加载必要的npm包
const cloud = require('wx-server-sdk')
const got = require('got');
const FormData = require('form-data');
cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  let form = new FormData();
  formData = JSON.parse(event.formData) // 通过event传递构建Form Data 
  for (let key in formData) {
    form.append(key, formData[key]);
    console.log(key); // 健   
  }
  var url = "http://www.xxxxx:8080" 
  let postResponse = await got(url + event.url, {
    method: 'POST', // post请求
    "headers": {
      "Accept-Language": "zh-CN",
    },
    body: form
  })

  return JSON.parse(postResponse.body) // 返回数据
}

调用云函数

在微信小程序的 .js 文件中调用HTTP请求云函数的模板。

wx.cloud.callFunction({
  name: 'http', // 创建的云函数名称
  data: {
    url: "/user/wx_Login",
    // 在这里放入 FormData 的参数
    formData: JSON.stringify({
		email: this.data.email,
		password: this.data.password,
    })
  },
  success: res => {
    console.log('[云函数] [http] 调用成功', res.result)
    if (res.result.code == 200) {
		app.globalData.userInfo = res.result.info
		console.log('登录成功', res)
    }
  },
  fail: err => {
    console.error('[云函数] [http] 调用失败', err)
  }
})

服务器端接收

服务器端我使用的是 Python 的 FastAPI 框架,其接收 FormData 的代码如下,以供参考。

@app.post("/user/wx_Login", tags=["账户系统"], name="移动端用户登录")
def wx_login(email: str = Form(...), password: str = Form(...)):
    print("====== POST: 移动端用户登录")
    connect = pymysql.connect(**config)
    cursor = connect.cursor()
    sql = "select userID,username,password,token from USER where email = '%s'" % email
    try:
        cursor.execute(sql)
        row = cursor.fetchone()
        userID = row['userID']
        if row:
            if row['password'] == password:
                userInfo = getUserInfo(userID)  # 获取用户信息
                return JSONResponse({"data": {"token": row['token']}, "info": userInfo, "code": 200, "message": '登录成功'})
            else:
                return JSONResponse({"code": 403, "message": '密码错误'})
        else:
            return JSONResponse({"code": 403, "message": '该用户不存在'})
    except:
        connect.rollback()
        raise
    finally:
        cursor.close()
        connect.close()
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值