微信小程序云开发-云函数发起https请求简易封装函数

一、前言

在日常的开发中,经常会遇到需要请求第三方API的情况,例如请求实名认证接口、IP转换地址接口等等。这些请求放在小程序前端的话,就需要把密钥放在客户端,在安全性上没这么高。文章来源地址https://www.yii666.com/blog/713474.html

因此,一般是放在云函数端去访问,小程序端传输对应的参数数值到云函数,然后云函数再去请求API接口。

本文简单封装了一下发起https请求函数,方便复用。

二、实现代码

const request = require("request");
/**
 * 发起网络请求
 * @param {object} paramObj 请求的参数对象
 */
const requestFun = (url, method, paramObj) => {
    // 请求数据
    const options = {
        timeout : 5000,  // 设置超时
        method : method, //请求方式
        url : url,
        headers : {
            "Content-Type" : "application/json",
        },
        body : paramObj,
        json : true,
    };
    // 发起请求
    return new Promise((resolve, reject) => {
        request(options, function(error, response) {
            if (error)
                resolve(error);
            resolve(response.body);
        });
    });
};
// get请求
const res = await requestFun(url, “GET”, {name: 小明,age:23})

// post请求
const res = await requestFun(url, “POST”, {name: 小明,age:23})

猜你喜欢

转载自blog.csdn.net/mo3408/article/details/132952538