前言
在 Flask 中設定 cookie 時,若其值含有中文,會被轉換為 8 進位 (Ex. \344\270\255\346\226\207\346\270\254\350\251\246
),在前端顯示時就無法正確顯示,這一篇文章來記錄一下解決方式。
Solution
目前有以下兩個解法:
- Solution 1: 前端將 8 進位轉為 16 進位,再將 16 進位轉成 UTF-8 字串
- Solution 2: 後端將其值做 Base64 encode, 前端再做 Base64 decode
Solution 1
前端將 8 進位轉為 16 進位,再將 16 進位轉成 UTF-8 字串:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
const convertHexToStr = (hexStr) => { let content = '';
for(let i = 0; i < hexStr.length; i += 2) { content += String.fromCharCode(parseInt(hexStr.substr(i, 2), 16)); }
return decodeURI(escape(content)); }
const convertOctToStr = (octStr) => { let octalList = octStr.split('\\'); let octalGroup = []; for(let i = 1; i < octalList.length; i += 3) { octalGroup.push(octalList.slice(i, i+3)); }
let result = ''; octalGroup.forEach((group) => { let word = '';
group.forEach((item) => { let hexStr = parseInt(item, 8).toString(16); word += hexStr; });
result += convertHexToStr(word); });
return result; }
const user = convertOctToStr(cookies.get('user'));
|
Solution 2
後端將 cookie 值做 Base64 encode:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import base64 from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/login', methods=['POST']) def login():
response = jsonify(status='success') response.set_cookie( key='user', value=base64.b64encode('中文名稱'.encode('utf-8')) )
return response
if __name__ == '__main__': app.run()
|
前端再做 Base64 decode:
1
| decodeURI(escape(atob(cookies.get('user'))))
|