gpt4 book ai didi

javascript - Flask,在 cookie 中设置 JSON,并在客户端对其进行解码(在 javascript 中)

转载 作者:行者123 更新时间:2023-11-28 22:50:54 25 4
gpt4 key购买 nike

我在 Flask 中设置一个 cookie,如下所示:

response.set_cookie('notice', value = json.dumps(someObject), max_age=None)

如果我在服务器上打印 json.dumps(someObject) 我得到:

{"message": "hello", "type": "success"}

在客户端变成:

"{\"message\": \"hello\"\054 \"type\": \"success\"}"

我想在 javascript 客户端上解码它到底是什么格式?

我想对其进行解码并将其传递给 angular.fromJson(),看起来至少没有转义(\")要做,但我很惊讶地看到\054(逗号的八进制 ASCII 代码)

最佳答案

Werkzeug 库引用了 cookie 值,以便在 Cookie 中安全使用 header ;这包括引用任何逗号、分号、双引号和反斜杠:

cookie_quoting_map = {
b',' : b'\\054',
b';' : b'\\073',
b'"' : b'\\"',
b'\\' : b'\\\\',
}

字母、数字和字符以外的任何其他内容 !#%&'~_`><@,:/$*+-.^|)(?}{=也被编码为八进制代码点。如果 cookie 中有任何转义值,则整个 cookie 也用双引号括起来。

如果您需要访问 JavaScript 中的 cookie 值,则必须再次对其进行解码。以斜杠和 3 位数字开头的值是八进制值;一个String.replace()调用应该做的:

function decode_flask_cookie(val) {
if (val.indexOf('\\') === -1) {
return val; // not encoded
}
val = val.slice(1, -1).replace(/\\"/g, '"');
val = val.replace(/\\(\d{3})/g, function(match, octal) {
return String.fromCharCode(parseInt(octal, 8));
});
return val.replace(/\\\\/g, '\\');
}

演示:

> // recreate properly escaped value
> var cookie = "\"{\\\"message\\\": \\\"hello\\\"\\054 \\\"type\\\": \\\"success\\\"}\""
> cookie
""{\"message\": \"hello\"\054 \"type\": \"success\"}""
> decode_flask_cookie(cookie)
"{"message": "hello", "type": "success"}"
> JSON.parse(decode_flask_cookie(cookie))
Object {message: "hello", type: "success"}

关于javascript - Flask,在 cookie 中设置 JSON,并在客户端对其进行解码(在 javascript 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22259779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com