请求封装wx.request
封装代码的文件命名:fetch.js
文件在小程序项目中的路径:XCX\utils\fetch.js
utils文件夹同pages文件夹同级
fetch.js
const reqUrl = 'https://www.xxx.com/';
const fetch = (url, data = {}, method, headers)=> {
return new Promise((resolve, reject) => {
wx.request({
url: reqUrl + url, //路径url
data, //参数
method, //post、get
header: headers, //请求头,可传递自定义请求头
success: res => { //请求发出成功返回结果,状态码200
resolve(res)
},
fail: (err) => { //请求发出失败
reject(err);
console.log(err)
},
complete: (res) => { //请求发出后
}
})
})
}
//导出
module.exports = {
fetch
}
其他页面使用例如:home.js使用
const { fetch } = require('../../utils/fetch.js'); //引入封装请求文件,注意路径
Page({
data: {
},
onLoad() {
this.getEquipList();
},
getEquipList() {
let url = '/api.getEquip';
let data = {
name:'123',
eq_No:50
}
//此处headers可自定义也可不,跟自己需求
let headers = {
xxxx:xxxxx
}
fetch(url, data, 'post', headers).then((res) => {
console.log('打印请求结果',res)
}).catch((err) => {
console.log('服务器请求错误!',err);
return;
})
}
})
© 版权声明
文章版权归作者所有,未经允许请勿转载。