jQuery Ajax、axios、fetch、weex、微信小程序(Android)保持session會話一致。

一、APP端(Android)的做法:

將第一次請求得到的 sessionId 塞到請求頭的Cookie裏面。sessionId 由後臺獲取後傳遞到前端

headers:{'Content-Type': 'application/json;charset=UTF-8', "Cookie":"JSESSIONID="+sessionId},  // Content-Type 自己看data參數傳輸的類型情況判斷要不要加或修改

微信小程序

參考:微信小程序之保持登錄狀態即session不改變(Java)

需要注意的:開發工具和手機調試時cookie的格式不一致,獲取session時不要在小程序端返回的數據 cookie獲取session(JSESESSIONID),開發工具和手機調試時cookie的格式不一致。在後端獲取sessionId後傳遞到前端使用

Android APP

weex 例子:

const stream = weex.requireModule('stream');  // 網絡請求模塊
stream.fetch({
    headers:{'Content-Type': 'application/json;charset=UTF-8', "Cookie":"JSESSIONID="+Vue.prototype.sessionId},  // Vue.prototype.sessionId 是一個全局變量,存儲sessionId
    method: 'POST',
	type: 'json',
	url: Vue.prototype.target+"/user/login",
	body: JSON.stringify(user)
}, (ret) => {
});

二、Web端做法(vue.js html5 等)

jQuery Ajax、axios、fetch請求時加上參數:xhrFields: {withCredentials: true},

axios例子:(其它請求同理)

axios 的引入要正確
axios.defaults.withCredentials = true;  // axios 的特殊,其它技術可不加
axios({
    xhrFields: {  // 保證每次請求的sessionid 相同
        withCredentials: true
    },
    method: 'post',
    timeout: 5000,
    url: url,
    data: {}
}).then(response => {
    console.log(response)
}).catch(error => {
    console.log(error);
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章