// 封装request请求
let ajaxTimes = 0; // 记录发送请求的次数
export default ((url, data = {}, header = {}, method = 'GET') => {
ajaxTimes++;
wx.showLoading({
title: '加载中...',
mask: true
});
// new Promise初始化promise实例的状态为pending
return new Promise((resolve, reject) => {
wx.request({
// es6中同名对象属性,属性名可以省略
url,
data,
enableCache: true,
enableHttp2: true,
enableQuic: true,
header,
method,
timeout: 0,
success: (result) => {
// 修改promise状态为成功状态resolved
resolve(result.data)
},
fail: (res) => {
// 修改promise状态为失败状态rejeced
reject(res)
},
complete: () => {
ajaxTimes--;
// 如果发送的请求,全部都返回了后才隐藏加载中
if (ajaxTimes === 0) {
wx.hideLoading();
}
}
})
})
})
使用:
import request from '../../utils/request'
var api = require('../../config/api')
.....
async searchSong() {
let result = await request(api.searchUrl, { keywords: inputValue, limit: 10 })
},
async getSong() {
let result = await request(api.songDetailUrl, data={id:1000},header={},method='POST')
},
api.js
var rootUrl = "http://127.0.0.1:3000/"
module.exports = {
searchUrl: rootUrl + "search/", // 根据用户输入内容进行模糊搜索
songDetailUrl: rootUrl + "song/detail/", // 获取音乐详情
}
如果报错:ReferenceError: regeneratorRuntime is not defined
记得选上:增强编译
另一种方法:
export const request = (params) => {
const rootUrl = "https://XXX.net/api/public/v1/"
return new Promise((resolve, reject) => {
wx.request({
...params,
url = rootUrl + params.url, // 对url进行拼接,传递过来的url只需要传递接口后半部分即可
success: (result) => {
resolve(result.data)
},
fail: (err) => {
reject(err)
},
});
})
}
使用:
import {request} from '../../request/request';
getBanners() {
request({url:'home/banner',header:{Cookie: 'xxxxxxx'}})
.then(result=>{
console.log(result)
})
},