现在是这样的 app.js 执行登录 登录的时候请求用code请求后端 返回的自定义token添加到封装的request请求上
但是现在因为异步 不知道怎么确定获取到返回的自定义tocken才执行封装的request
app.js
wx.login({
success: function(res) {
if (res.code) {
const params = {
appid: 'wx66e4ec7b580c2658',
grant_type: 'authorization_code',
js_code: res.code,
secret: '8028563818513852479da62c3004afc2'
}
handleLogin.loginServer(params).then((res) => {
console.log(res)
wx.setStorageSync('access_token', res.data)
wx.setStorageSync('login', 0)
// wx.setStorageSync('access_token', 'aaa')
})
}
else{
showToast()
}
},
fail:function(err){
showToast()
}
})
handleLogin.js
// 登录
const app = getApp()
function loginServer(params) {
let promise = new Promise(function(resolve, reject) {
wx.request({
url: `http://3b58503d.ngrok.io/20180507/net-cosrun-project/web/v1/activity/login`,
data: params,
method: 'POST',
success: function(res) {
resolve(res);
},
fail:function(err){
reject(err);
wx.setStorageSync('login', 1)
}
})
})
return promise
}
function showToast(content = '登录失败,请稍后再试') {
wx.showToast({
title: content,
icon: 'none'
})
}
module.exports = {
loginServer: loginServer,
showToast: showToast
}
封装的请求promise.js
const app = getApp()
const handleLogin = require('./handleLogin.js');
let token = ''
function request(url, params, method) {
const appid = 'miinno.com'
const secret = '123456'
const version = 'api/v1'
const timestamp = new Date().getTime()
const a = appid + 'APPID' + secret + 'SECRET' + timestamp
const sign = sha1(appid + 'APPID' + secret + 'SECRET' + timestamp)
token = sign + '.' + timestamp + '.' + version
// console.log(wx.getStorageSync('access_token'))
let promise = new Promise(function(resolve, reject) {
if(wx.getStorageSync('login')=='0'){
wx.request({
url: url,
data: params,
header: {
'X-Token-With': token,
'Authorization': `Miinno ${wx.getStorageSync('access_token')}`
},
method: method || 'GET',
success: function (res) {
// app.globalData.netWorkData = res.data
resolve(res);
if (res.data.hasOwnProperty('error')) {
console.log(url)
if (url != 'http://f63aca00.ngrok.io/20180507/net-cosrun-project/web/v1/vote/vote') {
wx.showModal({
title: '提示',
content: res.data.error.message,
success: function (res) {
if (res.confirm) {
} else if (res.cancel) { }
}
})
}
}
}
})
}
else{
console.log('aa')
// handleLogin.login(() => {
// })
}
});
return promise
}
求大神指教
小程序文档档中有说过吧,可以在
app.js
里设置一个状态和一个全局回调,别的页面的初始化在此状态完成之前都等待。isReady
和回调。app.isReady
的状态,看是现在立刻启动(.start()
)还是在回调之后再启动。