微信小程序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请求为例)

 1  bindSearchChange:function(e){
 2     var keyword = e.detail.value;
 3     wx.request({
 4       url:'xxxxxxxxx',
 5       data:{},
 6       header: {'Content-Type': 'application/json'},
 7       success: function(res) {
 8         console.log(res)
 9       }
10     })
11   }

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

 1 var rootDocment = 'hxxxxx';//你的域名
 2 function req(url,data,cb){
 3     wx.request({
 4       url: rootDocment + url,
 5       data: data,
 6       method: 'post',
 7       header: {'Content-Type': 'application/json'},
 8       success: function(res){
 9         return typeof cb == "function" && cb(res.data)
10       },
11       fail: function(){
12         return typeof cb == "function" && cb(false)
13       }
14     })
15 }
16  
17  
18 module.exports = {
19   req: req
20 }

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

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

 1 //app.js
 2 var http = require('service/http.js')
 3 App({
 4   onLaunch: function () {
 5     //调用API从本地缓存中获取数据
 6     var logs = wx.getStorageSync('logs') || []
 7     logs.unshift(Date.now())
 8     wx.setStorageSync('logs', logs)
 9   },
10   getUserInfo:function(cb){
11     var that = this
12     if(this.globalData.userInfo){
13       typeof cb == "function" && cb(this.globalData.userInfo)
14     }else{
15       //调用登录接口
16       wx.login({
17         success: function () {
18           wx.getUserInfo({
19             success: function (res) {
20               that.globalData.userInfo = res.userInfo
21               typeof cb == "function" && cb(that.globalData.userInfo)
22             }
23           })
24         }
25       })
26     }
27   },
28   globalData:{
29     userInfo:null
30   },
31   func:{
32     req:http.req
33   }
34 })

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

 1 var app = getApp()
 2 Page({
 3   data: {
 4     
 5   },
 6   onLoad: function (opt) {
 7     //console.log(opt.name)
 8    app.func.req('/api/get_data',{},function(res){
 9      console.log(res)
10     });
11   }
12 })

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

原文地址:https://www.cnblogs.com/chbyl/p/9746383.html