微信小程序使用request网络请求操作实例

2023-06-26,,

本文实例讲述了微信小程序使用request网络请求操作。分享给大家供大家参考,具体如下:

小程序提供了很多api,极大的方便了开发者,其中网络请求api是wx.request(object),这是小程序与开发者的服务器实现数据交互的一个很重要的api。

官方参数说明如下

OBJECT参数说明:

参数名 类型 必填 说明
url String 开发者服务器接口地址
data Object、String 请求的参数
header Object 设置请求的 header , header 中不能设置 Referer
method String 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
success Function 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'}
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

最简单的用法如下(以POST请求为例)

bindSearchChange:function(e){
 var keyword = e.detail.value;
 wx.request({
 url:'xxxxxxxxx',
 data:{},
 header: {'Content-Type': 'application/json'},
 success: function(res) {
 console.log(res)
 }
 })
}

下面我们把请求写在service文件下的http.js文件中,代码如下

var rootDocment = 'hxxxxx';//你的域名
function req(url,data,cb){
 wx.request({
 url: rootDocment + url,
 data: data,
 method: 'post',
 header: {'Content-Type': 'application/json'},
 success: function(res){
 return typeof cb == "function" && cb(res.data)
 },
 fail: function(){
 return typeof cb == "function" && cb(false)
 }
 })
}
module.exports = {
 req: req
}

其中module.exports是将req方法暴露出去使得别的文件中可以使用该方法,由于js函数是异步执行的,所以return 的是回调函数,而不是具体的数据

为了其他文件方便调用此方法,我们在根目录的app.js文件中将其注册成为全局函数,如下

//app.js
var http = require('service/http.js')
App({
 onLaunch: function () {
 //调用API从本地缓存中获取数据
 var logs = wx.getStorageSync('logs') || []
 logs.unshift(Date.now())
 wx.setStorageSync('logs', logs)
 },
 getUserInfo:function(cb){
 var that = this
 if(this.globalData.userInfo){
 typeof cb == "function" && cb(this.globalData.userInfo)
 }else{
 //调用登录接口
 wx.login({
 success: function () {
  wx.getUserInfo({
  success: function (res) {
  that.globalData.userInfo = res.userInfo
  typeof cb == "function" && cb(that.globalData.userInfo)
  }
  })
 }
 })
 }
 },
 globalData:{
 userInfo:null
 },
 func:{
 req:http.req
 }
})

这时这个req就是全局的了,在调用时我们可以使用getApp.func.req()来调用,具体如下

var app = getApp()
Page({
 data: {
 },
 onLoad: function (opt) {
 //console.log(opt.name)
 app.func.req('/api/get_data',{},function(res){
 console.log(res)
 });
 }
})

微信小程序提供了很多api,包括网络,媒体,数据等,也提供了很多组件,使开发小程序变得很方便。

希望本文所述对大家微信小程序开发有所帮助。

《微信小程序使用request网络请求操作实例.doc》

下载本文的Word格式文档,以方便收藏与打印。