首页 新闻 会员 周边

怎么使用微信小程序request封装

0
悬赏园豆:20 [待解决问题]

// ###封装请求是否自动带上token

const Api_Base_Url = 'https://***.com';

const Request = (url, method, data = {}) => {
return new Promise((resolve, reject) => {
wx.request({
url: Api_Base_Url + url,
method: method,
data: data,
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success(res) {
resolve(res.data)
},
fail(error) {
reject(error)
}
})
})
}
const HTTP = (url, method, data, isToken = true) => {
// ###isToken请求是否自动带上token值,默认为true
return new Promise((resolve, reject) => {
if (isToken) {
// ###请求带token
let token = wx.getStorageSync('token')
if (token) {
// ###缓存有token直接用
data = Object.assign({
openId: token
}, data)
Request(url, method, data).then(res => {
resolve(res)
})
} else {
// ###缓存没有token,用code换取
wx.login({
success: res => {
if (res.code) {
getUserAuthor({
code: res.code
}).then(res => {
wx.setStorageSync('token', res.data.openid)
data = Object.assign({
openId: res.data.openid
}, data)
Request(url, method, data).then(res => {
resolve(res)
})
})
}
}
})
}
} else {
// ###请求不带token
Request(url, method, data).then(res => {
resolve(res)
})
}
})
}

let getUserAuthor = (code) => {
return Request('/auth/getUserAuthor', 'get', code)
}

let getGoldCount = (data) => {
return HTTP('/mini/user/getGoldCount', 'get', data, true)
}

let getGoods = (data) => {
return HTTP('/goods/getGoods', 'get', data, false)
}

export default {
getGoldCount: getGoldCount,
getGoods: getGoods
}

加压的主页 加压 | 初学一级 | 园豆:184
提问于:2023-10-12 15:16
< >
分享
所有回答(1)
0

您已经成功封装了一个用于在微信小程序中进行请求的函数。这个封装包括了是否自动带上token的选项。以下是如何使用您封装的请求函数的示例:

导入封装的请求函数:
javascript

import HTTP from 'path-to-your-HTTP.js'; // 替换为实际文件路径
发起请求:
javascript
Copy code
// 使用带有token的请求
HTTP.getGoldCount({ someData: 'data' })
.then(response => {
// 处理成功的响应
console.log('Success:', response);
})
.catch(error => {
// 处理错误的响应
console.error('Error:', error);
});

// 使用不带token的请求
HTTP.getGoods({ someData: 'data' })
.then(response => {
// 处理成功的响应
console.log('Success:', response);
})
.catch(error => {
// 处理错误的响应
console.error('Error:', error);
});
在上面的示例中,您首先导入了封装的HTTP对象。然后,您可以使用导入的函数发起请求,传递相应的URL、请求方法、数据和是否需要带token的选项。成功时,您可以处理响应数据;失败时,您可以处理错误。

确保替换示例中的数据和路径为您实际的需要,以适应您的微信小程序应用。此外,如果需要更多的自定义选项,您可以扩展封装的请求函数以支持您的需求。

Technologyforgood | 园豆:5992 (大侠五级) | 2023-10-12 19:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册