简体   繁体   English

如何使用sockets.io/node.js/javascript转义mysql特殊字符

[英]How to escape mysql special characters with sockets.io/node.js/javascript

I am using sockets.io to insert user-generated messages into MySQL, but I'm running into issues inserting records with an apostrophe. 我使用sockets.io将用户生成的消息插入MySQL,但我遇到插入带撇号的记录的问题。 I've been trying to use the replace() method on the client side script, but the input text is passing with the apostrophe. 我一直在尝试在客户端脚本上使用replace()方法,但输入文本是使用撇号传递的。

  socket.on('refresh feed',function(msg){
        str=msg.replace("'", "\'");
        alert(str);
    $("#chtxt").append(str + '<br />');
  });

The above attempt will alert any string without the special character, but does not alert when it exist. 上述尝试将在没有特殊字符的情况下警告任何字符串,但在存在时不会发出警报。 I believe that I'm actually alerting after the message has been sent to sockets. 我相信在消息发送到套接字之后我实际上是发出警报。

So, I tried adapting this code which watches for the enter key press to also watch for the apostrophe, with no luck there either. 因此,我尝试调整此代码,该代码监视输入键按下以观察撇号,也没有运气。

  $('#omnibox').keypress(function (e) {
    var key = e.which;
    if(key == 13)  // the enter key code
    {
      $('input[name = "clicky"]').click();
      return false;  
    }
    if(key == 222)  // the apostrophe key code
    {
            alert('Apostrophe!')
      return false;  
    }
    });

I researched the question of how to replace special characters for MySQL using javascript but found outdated stacks explaining why client-side validation for this is not a good idea. 我研究了如何使用javascript替换MySQL的特殊字符的问题,但发现过时的堆栈解释了为什么客户端验证不是一个好主意。

That's fine. 没关系。 If I shouldn't do this client side, I need to know then how to do it in my server.js node script, then. 如果我不应该这样做客户端,那么我需要知道如何在我的server.js节点脚本中执行此操作。 It is still javascript, so a solution on either side, provided it's secure would be great. 它仍然是javascript,所以任何一方的解决方案,只要它是安全的将是伟大的。

Server-side code: 服务器端代码:

var add_status = function (status,callback) {
    pool.getConnection(function(err,connection){
        if (err) {
          callback(false);
          return;
        }
    connection.query("INSERT INTO `videosub` (`url`) VALUES ('"+status+"')",function(err,rows){
            connection.release();
            if(!err) {
              callback(true);
            }
        });
     connection.on('error', function(err) {
              callback(false);
              return;
        });
    });
}

Thanks! 谢谢!

Don't do it 不要这样做

You are asking about the wrong solution to the problem. 您在问这个问题的错误解决方案。

To replace the apostrophes with backslash-apostrophes you might use: 要用反斜杠撇号替换撇号,您可以使用:

str = msg.replace(/'/g, '\\\'');

but you should not do that . 但你不应该这样做 I am only providing that info because that's what your question asks about but read below. 我只提供该信息,因为这是您的问题所要求的,但请阅读以下内容。

Why it's a bad idea 为什么这是一个坏主意

You shouldn't do it on the client side and you shouldn't do in on the server side either. 您不应该在客户端执行此操作,也不应该在服务器端执行此操作。 If avoiding SQL injection vulnerabilities was a simple matter of replacing apostrophes with backslash-apostrophes then it wouldn't be an issue. 如果避免SQL注入漏洞是一个简单的问题,用反斜杠撇号替换撇号,那么这不会是一个问题。 Unfortunately it's more complicated. 不幸的是,它更复杂。

Having the info that you provided it's even impossible to tell whether backslash-apostrophe would even do what you expect in the first place without seeing your code that actually makes the database queries. 拥有你提供的信息,甚至无法判断反斜杠撇号是否会在没有看到实际产生数据库查询的代码的情况下首先执行您所期望的操作。 But it doesn't matter because you should never ever do that. 但这并不重要,因为你永远不应该这样做。 Never. 决不。 See those answers to see why - those questions are not about SQL injections but the code examples included SQL injection vulnerabilities and the answers explain it: 查看这些答案以了解原因 - 这些问题与SQL注入无关,但代码示例包含SQL注入漏洞,答案解释如下:

Obligatory comic strip 强制性漫画

在此输入图像描述

What you should do instead 你应该做什么

That having been said, you didn't tell what module you're using to query the database but no matter if you're using the mysql module or Sequelize or anything worth its salt, there should always be a mechanism of interpolating variables in a safe manner without manually escaping and concatenating the strings. 话虽如此,你没有告诉你用什么模块来查询数据库但无论你是使用mysql模块还是Sequelize还是其他任何有价值的东西,都应该总是有一种插入变量的机制。安全的方式,而无需手动转义和连接字符串。

Examples 例子

You didn't show even a single line of code that is relevant here so I cannot tell you how to fix it but consider this example: 您甚至没有显示与此相关的单行代码,因此我无法告诉您如何修复它,但请考虑以下示例:

Unsafe: 不安全:

connection.query(
  "SELECT * FROM player WHERE nick = '"
  + data.login + "' AND pass = '" + data.pass + "'",
  function (err, rows) {
    //...
  }
);

Still unsafe, complex, unreadable, unmaintainable and unreliable: 仍然不安全,复杂,难以理解,不可维护和不可靠:

connection.query(
  "SELECT * FROM player WHERE nick = '"
  + data.login.replace(/'/g, '\\\'') + "' AND pass = '" + data.pass.replace(/'/g, '\\\'') + "'",
  function (err, rows) {
    //...
  }
);

Safe and simple: 安全简单:

connection.query(
  "SELECT * FROM player WHERE nick = ? AND pass = ?", [data.login, data.pass],
  function (err, rows) {
    // ...
  }
);

More info 更多信息

For more info see the docs: 有关更多信息,请参阅文档:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM