微信小程序通過雲函數請求 http 協議 api 接口

微信小程序請求接口需要把接口域名添加到小程序官方後臺的 request 域名列表裏,並且還要是 https 協議的。使用微信自帶的雲開發,並且新建雲函數,可以繞過這個限制,直接訪問 http 協議的接口也沒有問題!

// 雲函數入口文件
const cloud = require('wx-server-sdk')
var request = require('request')
cloud.init()

// 雲函數入口函數
exports.main = async (event, context) => {
    //這裏寫普通話成績查詢方式
    return new Promise((resolve, reject) => {
        request({
            url: event.url,
            method: event.method || 'POST',
            json: event.json || false,
            headers: event.headers || null,
            body: event.body || null,
            form: event.form || null,
        }, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                try {
                    resolve(body)
                } catch (e) {
                    reject()
                }
            }
        })
    })
}

參考鏈接:

1、https://developers.weixin.qq.com/community/develop/article/doc/000cc8398b012864f398db33556413

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章