如何在WxHttpService中添加自己的实现?
chunfytseng opened this issue · comments
chunfytseng commented
比如:
` this.interceptors.use({
request(request) {
request.header = request.header || {};
request.header['content-type'] = 'application/json';
if (request.url.indexOf('/yse') > -1 && request.url.indexOf('/create_user') < 0) {
var vsk = wx.getStorageSync('sk');
if (!sk) {
async function fn1() {
var promise = new Promise(function (resolve, reject) {
wx.login({
success: function (res) {
resolve(res.code);
}
});
});
var code = await promise;
// 我始终无法设置code到header,这是一个异步的,怎么同步设置呢,求解,谢谢!
request.header['code'] = code;
}
} else {
request.header['sk'] = sk;
}
}
wx.showLoading({
title: '加载中...',
})
return request;`
skyvow commented
@chunfytseng 不明白你的意思
chunfytseng commented
我的逻辑是这样的:
request.header = request.header || {};
request.header['content-type'] = 'application/json';
if (request.url.indexOf('/yse') > -1 && request.url.indexOf('/create_user') < 0) {
var vsk = wx.getStorageSync('sk');
if (!sk) {
wx.login({
success: function (res) {
request.header['code'] = res.code;
}
});
}
} else {
request.header['sk'] = sk;
}
}
wx.showLoading({
title: '加载中...',
})
return request;
header里面始终没有vcode,而且wx.login这个方法是不是异步的,是不是还没有获取到code就返回request了,如果是这种情况怎么处理呢?我使用promise也无济于事,求解答。
skyvow commented
你理解是对的,由于是异步的无法成功设置 code,login 不应该在这里的,逻辑有问题。code 直接当参数传给 request 才对啊。
chunfytseng commented
嗯,你说的是对的,按道理是这样,但是我的程序是指需要openID就可以了,其他信息我不需要,我的判断逻辑是这样的,检查sk,sk存在就携带sk,不存在就携带code,这个逻辑在每次请求都要做,因为我把他放在了这里统一处理。请问如果我放在这里处理,怎么保证能成功设置呢,麻烦给一个实例,还望解答,谢谢你。