NodeJS Express如何取消转义HTML实体以供显示目的

8
我将在NodeJS、Express、Angular JS和Google应用引擎数据存储中构建Web应用程序。
我正在学习Node。 我创建了一个表单,在将用户输入插入数据库之前“净化”(转义)它。 我遵循MDN网站上NodeJS教程创建了这段代码:
//Trim and escape all inputs
req.sanitize('requester').escape();
req.sanitize('requester').trim();
req.sanitize('dataowner').escape();
req.sanitize('dataowner').trim();
req.sanitize('requested_filepath_list').escape();
req.sanitize('requested_filepath_list').trim();

“requested_filepath_list”是一个UNIX文件路径列表。
当用户提交请求时,它以“转义”的格式存储在数据库中。
//Escaped data
/top/example/test123.txt

问题: 如何“取消转义”数据以便进行显示?

//Desired output
/top/example/test123.txt

我尝试了unescape函数,但似乎不起作用,它只是返回相同的输出。
let escape_str = '/top/example/test123.txt';
let unescaped_str = unescape(escape_str);
console.log('unescaped_str: ' + unescaped_str);

//Output
unescaped_str: /top/example/test123.txt

//Desired output
/top/example/test123.txt

1
为什么要首先存储转义字符?将其作为普通文本存储在数据库中即可。 - Keith
1
有趣的观点,但考虑到安全原因,我认为最好将其转义后存储。 - pengz
2个回答

6
我使用了'he'库来实现这个要求。
以下是详细信息的帖子:如何解码包含特殊HTML实体的字符串? 这里是该库。我能够使用npm install安装它。 https://www.npmjs.com/package/he 示例解决方案:
const he = require('he');

let escape_str = '/top/example/test123.txt';

let unescaped_str = he.decode(escape_str);

console.log('unescaped_str ' + unescaped_str);

-1
你可以试试这个 :)
const querystring = require('querystring');
querystring.unescape(escape_str);

我安装了querystring模块并尝试了这些步骤,但字符串仍然没有改变...const querystring = require('querystring');let escape_str = '/top/example/test123.txt';let unescaped_str = querystring.unescape(escape_str);console.log('unescaped_str ' + unescaped_str);输出 /top/example/test123.txt - pengz
也许这只适用于Node版本9.0。我使用的是Node 8.4.0。 https://nodejs.org/api/querystring.html#querystring_querystring_unescape_str - pengz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接