微信提供了api,开发者可以通过wx.request来获取服务器的数据和传递数据。虽然api提供了很大的方便,但是调用多个接口时,代码重复性太高,我们可以进一步封装。
将官方文档中wx.request的参数贴上,方便阅读
针对3点问题对wx-request进行简单封装 1、网络请求都写在Page里,每个请求都要重复的写wx.request以及一些基础配置 2、每个页面里都要处理相同类型的异常 3、后端返的http status code为200以外时,并不能直接进入fail对应函数进行处理
- 在项目utils文件夹内新建 request.js 文件,并进行配置
const app = getApp()
var baseurl = "http://127.0.0.1:3000" // 域名接口地址
const request = (url, options) => {
// 当发起请求的时候,界面出现“数据加载中...”的Loading界面
wx.showLoading({
title: '数据加载中...',
mask: true
})
return new Promise((resolve, reject) => {
wx.request({
url: baseurl + url, //请求的接口地址
timeout: 5000, // 请求超时时间
method: options.method, //配置method方法
data: options.method === 'GET' ? options.data : JSON.stringify(options.data), //如果是GET,GET自动让数据成为query String,其他方法需要让options.data转化为字符串
header: {
'Content-Type': 'application/json; charset=UTF-8',
}, //header中可以添加token值等
success(request) { //监听成功后的操作
if (request.statusCode === 200) {
resolve(request.data)
} else {
reject(request.data)
}
},
fail(error) { //返回失败也同样传入reject()方法
reject(error.data)
},
complete: ()=> {
// 请求完成关闭Loading
wx.hideLoading();
}
})
})
}
//封装get方法
const get = (url, options = {}) => {
return request(url, {
method: 'GET',
data: options
})
}
//封装post方法
const post = (url, options = {}) => {
return request(url, {
method: 'POST',
data: options
})
}
//封装put方法
const put = (url, options) => {
return request(url, {
method: 'PUT',
data: options
})
}
//封装remove方法,DELETE关键字不能声明
const remove = (url, options = {}) => {
return request(url, {
method: 'DELETE',
data: options
})
}
module.exports = {
get,
post,
put,
remove
}
2.在 app.js 中引用声明 request.js 来做到全局使用
import $http from '/utils/request.js'
App({
//request请求
$http
})
3.页面内实现请求 index.js
const app = getApp()
Page({
onLoad(options){
let data = {}
app.$http.get('/api/client/getAllArticle', data).then(res =>{
console.log(res)
}).catch(err => {
console.log(err)
})
}
})