微信小程序API详解
小程序开发框架提供丰富的微信原生 API,可以方便的调起微信提供的能力,如获取用户信息,本地存储,支付功能等。
-
根据api的名称大体可以分为如下三类
- 事件监听 API
- 同步 API
- 异步 API
-
微信API基本使用
- 界面API:加载提示
- wx.showLoading
- wx.hideLoading
- wx.showToast
- wx.hideToast
- 调用后台接口
- 测试接口
- wx.request
wx.request({ url: 'http://localhost:3000/data', success: (res) => { // console.log(that) this.setData({ info: res.data }) } })
- 界面API:加载提示
实例-express模拟接口及调用
第一步:新建demo文件夹下的页面demo.js中,调用接口
注意:访问接口时,需要授权:小程序开发工具——>右上角详情——>本地设置,下面的合法域名
图例:
// pages/demo/index.js
const app = getApp()
// console.log(app)
// 不要手动调用生命周期函数
// app.onLaunch()
// 自定义函数可以手动调用
app.foo()
Page({
/**
* 页面的初始数据
*/
data: {
msg: 'nihao',
info: {}
},
getData: function () {
// 调用后台接口获取数据,更新页面 不用that,this取值为undefind
// let that = this
// wx.request({
// url: 'http://localhost:3000/data',
// success: function (res) {
// // console.log(that)
// that.setData({
// info: res.data
// })
// }
// })
//两种写法 同效 箭头函数this指向父级
wx.request({
//接口地址
url: 'http://localhost:3000/data',
success: (res) => {
// console.log(that)
this.setData({
info: res.data
})
}
})
},
handleTap: function () {
// setData更新数据是同步的
// 但是页面内容的变化时异步的
this.setData({
msg: 'hello'
}, () => {
// 该回调函数执行时,页面内容已经完成了更新
console.log('页面内容已经更新')
})
// 当这里获取到最新数据时,页面的内容有可能还没有更新
console.log(this.data.msg)
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
// 提示加载成功
// wx.showToast({
// title: '加载完成...'
// })
// wx.showLoading({
// title: '正在加载...'
// })
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
// setTimeout(function() {
// wx.hideLoading()
// }, 3000)
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
第二步:在某一层级新建文件夹myapi,并在当前文件夹下的命令行窗口,安装express包
npm i express
安装成功之后,通过node index.js
启动服务器
第三步:在myapi文件夹下新建文件index.js,定义接口
const express = require('express');
const app = express();
app.get('/data', (req, res) => {
//第一个接口
// res.send('Hello World')
//第二个接口
let info = {
username: 'lisi',
age: 12
}
res.json(info)
})
app.listen(3000, () => {
//监控是否请求成功
console.log('running...')
})
第四步:访问页面
在demo文件夹下的wxml中
<my-nav navData='{{["apple", "orange", "banana"]}}'/>
<view>
{{info.username + '--------' + info.age}}
</view>
<view>
<!-- <button bindtap='handleTap'>点击</button> -->
<button bindtap='getData'>点击</button>
</view>
显示:
点击后验证是否得到数据,页面变化
接口调用注意事项
-
接口调用需要配置权限
- 如果是开发环境,可以不做权限验证,配置开发工具,点击工具的如下菜单
- 下一步勾选如下选框
- 如果小程序上线后,需要调用接口,那么需要在自己小程序管理后台进行域名权限配置
- 接口调用的基本使用
- 如果小程序上线,那么调用的url地址必须是 https 协议(https协议需要后台支持)
- 本地测试接口可以使用http协议
wx.request({
url: 'http://localhost:3000/data',
success: function(res) {
// 这里获取响应结果
console.log(res)
that.setData({
msg: res.data
})
}
})
- 本地测试接口可以使用http协议
wx.request({
url: 'http://localhost:3000/data',
success: function(res) {
// 这里获取响应结果
console.log(res)
that.setData({
msg: res.data
})
}
})