1. 官方文档指南
2. 使用教程
RequestTask wx.request(Object object)
功能描述
发起 HTTPS 网络请求。使用前请注意阅读相关说明。
参数
Object object
属性 | 类型 | 默认值 | 必填 | 说明 |
---|---|---|---|---|
url | string | 是 | 开发者服务器接口地址 | |
data | string/object/ArrayBuffer | 否 | 请求的参数 | |
header | Object | 否 | 设置请求的header,header中不能设置Referer。默认为 application/json | |
timeout | number | 否 | 超时间,单位为毫秒,默认值为 60000 | |
method | string | GET | 否 | HTTP请求方法 |
dataType | string | gson | 否 | 返回的数据格式 |
responseType | string | text | 否 | 响应的数据类型 |
success | function | 否 | 接口调用成功的回调函数 | |
fail | function | 否 | 接口调用失败的回调函数 | |
complete | function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
object.success 回调函数
参数
Object res
属性 | 类型 | 说明 |
---|---|---|
data | string/Object/Arraybuffer | 开发者服务器返回的数据 |
statusCode | number | 开发者服务器返回的 HTTP 状态码 |
header | Object | 开发者服务器返回的 HTTP Response Header |
cookies | Array | 开发者服务器返回的 cookies,格式为字符串数组 |
profile | Object | 网络请求过程中的一些调试信息,查看详细说明 |
exception | Object | 网络请求过程中的异常信息,例如httpdns重试等 |
useHttpDNS | boolean | 最终请求是否使用了HttpDNS(仅当enableHttpDNS传true时返回此字段) |
object.fail 回调函数
参数
Object err
属性 | 类型 | 说明 |
---|---|---|
errMsg | String | 错误信息 |
errno | Number | Errno 错误码,errno错误码的详细说明参考 Errno 错误码 |
更多详情请查看官方文档 | 更多详情请查看官方文档 | 更多详情请查看官方文档
3. 代码封装
- 新建一个包,取名叫net ,在包下面新建request.js文件,项目结构示意图如下:
- 在request.js 定义 WxRequest类
class WxRequest {
//用来控制并发请求,加载框显示问题
queue = []
//设置默认请求参数
defaults = {
baseURL: '', //请求基准地址
url: '', //接口请求路径
data: null, //请求参数
method: "GET", //请求方式,默认GET请求
header: { //设置请求头
'content-type': 'application/json'
},
timeout: 60000, //默认请求超时时间为1分钟
isLoading: true //控制是否开启loading
}
//定义拦截器对象
//需要包含请求拦截器,和响应拦截器
interceptors = {
//请求拦截器
//在请求发送之前,对请求参数进行处理
request: (config) => {
return config
},
//响应拦截器
//在服务器响应数据之后,对服务器响应的数据进行逻辑处理
response: (response) => {
return response
}
}
constructor(params = {}) {
//使用Object.assign合并参数
//注意事项:需要将传入的参数覆盖默认的参数,因此通过构造方法传入的参数需要放在最后
this.defaults = Object.assign({}, this.defaults, params)
}
request(options) {
return new Promise((resolve, reject) => {
//拼接完整的请求地址
options.url = this.defaults.baseURL + options.url
//合并请求参数
options = { ...this.defaults, ...options }
//在请求发送之前,添加loading效果
if (options.isLoading) {
if (this.queue.length === 0) {
wx.showLoading({
title: '加载中...',
})
}
//像队列中添加标识
this.queue.push('queueWhat')
}
//在请求发送之前,调用请求拦截器
options = this.interceptors.request(options)
wx.request({
//解构写法
...options,
//接口调用成功的回调函数
success: (res) => {
//根据日志打印结果,请注意当我们接口报404时,也会执行success这个方法
//响应拦截器
const mergeRes = Object.assign({}, res, { config: options })
resolve(this.interceptors.response(mergeRes))
},
//接口调用失败的回调函数
fail: (error) => {
const mergeErr = Object.assign({}, error, { config: options })
reject(this.interceptors.response(mergeErr))
},
//接口调用结束的回调函数(调用成功、失败都会执行)
complete: () => {
if (options.isLoading) {
this.queue.pop()
if (this.queue.length === 0) {
wx.hideLoading()
}
}
}
})
})
}
//封装GET方法
get(url, data = {}, config = {}) {
return this.request(Object.assign({ url, data, method: 'GET' }, config))
}
//封装DELETE方法
delete(url, data = {}, config = {}) {
return this.request(Object.assign({ url, data, method: 'DELETE' }, config))
}
//封装POST方法
post(url, data = {}, config = {}) {
return this.request(Object.assign({ url, data, method: 'POST' }, config))
}
//封装PUT方法
put(url, data = {}, config = {}) {
return this.request(Object.assign({ url, data, method: 'PUT' }, config))
}
}
//一定记得要导出
export default WxRequest
- 在net包下新建http.js文件,导入 WxRequest
import WxRequest from './request'
//实例化 WxRequest
const instance = new WxRequest({
//请填写自己后台的接口地址
baseURL: 'http://example.php:8080/api',
timeout: 60000
})
//配置请求拦截器
instance.interceptors.request = (config) => {
//可以在这里做一些逻辑处理~~~~~
console.log('开始发送请求啦------>' + JSON.stringify(config))
return config
}
//配置响应拦截器
instance.interceptors.response = (response) => {
//可以在这里做一些逻辑处理~~~~~
console.log('响应结果------>' + JSON.stringify(response))
return response
}
//记得要导出
export default instance
4. 如何使用?
- test.wxml
<!--pages/test/test.wxml-->
<view class="container-demo">
<button type="primary" size="mini" bind:tap="httpGet" >网络请求测试</button>
<text>{{userInfo}}</text>
</view>
- test.wxss
/* pages/test/test.wxss */
.container-demo{
display: flex;
padding: 100rpx;
flex-direction: column;
gap: 20rpx;
}
- test.js
// pages/test/test.js
//导入网络模块
import http from '../../net/http'
Page({
/**
* 页面的初始数据
*/
data: {
userInfo: '默认用户信息暂无'
},
//第一种写法(推荐使用 await + async的形式使用)
async httpGet() {
const res = await http.get('/login',
{'username': 'yihuangxing','password': '123456'},
{ isLoading: true })
this.setData({
userInfo: JSON.stringify(res.data)
})
},
//第二种写法
// httpGet() {
// http.get('/login',
// {'username':'yihuangxing','password': 123456},
// {isLoading:true})
// .then((res)=>{
// this.setData({
// userInfo: JSON.stringify(res.data)
// })
// })
// },
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})
温馨提示:
调用方法,获取响应数据 形式用两种:
- 使用
then
拿到响应结果- 使用
async
+await
拿到响应结果 (推荐使用)