app.js全局数据中添加header
globalData: {
userInfo: null,
header: {
'Cookie': ''
}
}
test.js
const app = getApp()
Page({
data: {
imgUrl: '' ,
result: ''
},
onLoad() {
this .initCaptcha();
},
initCaptcha() {
let url = '{域名}/Captcha/Index' ; // 空请求 为了拿到sessionId
wx.request({
header: app.globalData.header,
url,
data:{},
success: (res) => {
this .setSessionId(res);
this .downloadCaptcha();
}
})
},
downloadCaptcha(){
let url = '{域名}/Captcha/Generate?' + new Date().getTime();
wx.downloadFile({
header: app.globalData.header, // down时是没有sessionId
url,
success: (res) => {
console.log(res);
this .setData({
imgUrl:res.tempFilePath
});
}
})
},
refreshCaptcha() {
this .initCaptcha();
},
setSessionId(res) {
let cookieStr = res.header[ 'Set-Cookie' ];
// app.globalData.header.Cookie = cookieStr;
if (cookieStr){
let cookies = cookieStr.split( '; ' )
if (!cookies || cookies.length <= 0)
return ;
cookies.forEach(
(v) => {
const str = v.split( '=' );
if (str[0] && str[0] == 'PHPSESSID' ) {
let sessionId = decodeURI(str[1]);
app.globalData.header.Cookie = `PHPSESSID=${sessionId}`;
}
}
);
}
},
onSubmit(e){
let { code } = e.detail.value;
let url = '{域名}/Captcha/Validate' ;
wx.request({
header: app.globalData.header,
url,
data: {code},
success: (res) => {
console.log(res);
this .initCaptcha();
this .setData({
result:res.data.message
})
}
})
}
})