问题描述
有没有让JavaScript字符串传递给NodeJS友好的MySQL?我试图传递一个电子邮件地址到我的NodeJS服务器和查询到MySQL数据库。当正常的文本(如用户名)正常工作,但电子邮件地址不。使用逃避是不正确的答案,因为它不意味着SQL插入。我假设我需要PHP函数 mysql_real_escape_string()
的一些内容。
Is there away to make a javascript string being passed to NodeJS friendly for MySQL? I'm trying to pass an email address to my NodeJS server and query into MySQL database. When doing regular text such as a username works fine, but the email address doesn't. Using escape clearly is not the right answer as it is not meant for SQL insertion. I'm assuming I need something on the lines of the PHP function mysql_real_escape_string()
.
推荐答案
事实证明,mysql_real_escape_string()非常简单。 :
It turns out that mysql_real_escape_string() is pretty trivial. According to the documentation:
实际上听起来很简单,你可以这样做: / p>
Sounds pretty simple, actually. You could do something like this:
function mysql_real_escape_string (str) {
return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
switch (char) {
case "\0":
return "\\0";
case "\x08":
return "\\b";
case "\x09":
return "\\t";
case "\x1a":
return "\\z";
case "\n":
return "\\n";
case "\r":
return "\\r";
case "\"":
case "'":
case "\\":
case "%":
return "\\"+char; // prepends a backslash to backslash, percent,
// and double/single quotes
}
});
}
注意:我没有通过任何类型的单元测试或安全测试来运行,但它似乎正常工作 - 只是作为一个额外的好处,它转义选项卡,后退空间和'%',因此它也可以用于LIKE查询,根据(不像PHP原创)。
NOTE: I haven't run this through any sort of unit test or security test, but it does seem to work -- and, just as an added bonus, it escapes tabs, backspaces, and '%' so it can also be used in LIKE queries, as per OWASP's recommendations (unlike the PHP original).
我知道 mysql_real_escape_string()
是字符集感知,但我不知道有什么好处添加。
I do know that mysql_real_escape_string()
is character-set-aware, but I'm not sure what benefit that adds.
有一个很好的讨论这些问题。
There's a good discussion of these issues over here.
这篇关于使一个javascript字符串sql友好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!