微信開發(fā)工具訪問外部網絡API可以通過微信公眾平臺配置域名,實現(xiàn)本地和真機調試
但是對于wx.request()訪問https://api.weixin.qq.com則不適用,所以我們采用云函數(shù)來訪問https://api.weixin.qq.com,以獲取access_token為例,步驟如下:
1、新建云函數(shù),我的當前環(huán)境為cloud1,在該文件下新建obtainAccess文件夾,詳細的云函數(shù)搭建請自行搜索
2、obtainAccess文件夾中index.js中的內容如下
const cloud = require('wx-server-sdk')
var rp = require('request-promise'); //npm install request-promise 先安裝這個命令(cmd),詳細步驟請自行搜索,通過這行代碼可以訪問https://api.weixin.qq.com
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
});
// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext();
var options = {
uri:encodeURI('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的秘鑰'),// encodeURI()可把字符串作為 URI 進行編碼,傳遞中文到第三方接口不會將中文亂碼
method:'GET',
json:true
}
return await rp(options)
.then(function (res) {
return res
})
.catch(function (err) {
return '失敗'
});
}
結果:成功獲取access_token
3、調用,微信開發(fā)工具隨便一個普通頁面,如index.wxml,index.js中文章來源:http://www.zghlxwxcb.cn/news/detail-563730.html
<view bindtap="btn">點擊</view>
Page({
btn(){
wx.cloud.callFunction({
name:'obtainAccess',
success:res=>{
console.log(res);
}
})
},
onLoad() {
}
})
結果顯示如圖:文章來源地址http://www.zghlxwxcb.cn/news/detail-563730.html
到了這里,關于關于微信開發(fā)工具無法使用wx.request()訪問https://api.weixin.qq.com的解決方案的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!