简体   繁体   English

Node.js:防止 SQL 查询被 SQL 注入

[英]Node.js: Preventing SQL Queries from SQL Injections

I a developing a REST API with Node.js, using AWS Lambda and API Gateway.我使用 AWS Lambda 和 API Gateway 使用 Node.js 开发 REST API。 I am using MySQL database.我正在使用 MySQL 数据库。 I am a Java guy and very new to Node.JS.我是一个 Java 人,对 Node.JS 非常陌生。 Just one day old.才一天。

I realised that there are multiple ways to prevent SQL INjection in Node.js.我意识到有多种方法可以防止 Node.js 中的 SQL 注入。 Below is my code下面是我的代码

const mysql = require('mysql');
const PropertiesReader = require('properties-reader');

const prop = PropertiesReader('properties.properties');

const con = mysql.createConnection({
  host     : prop.get('server.host'),
  user     : prop.get("server.username"),
  password : prop.get("server.password"),
  port     : prop.get("server.port"),
  database : prop.get("server.dbname")
});


exports.getRoleByID = (event, context, callback) => {

  const { id } = event.queryStringParameters;
  console.log("id", id);

  // allows for using callbacks as finish/error-handlers
  context.callbackWaitsForEmptyEventLoop = false;
  const sql = "select * from role where idrole = ?";
  con.query(sql, [id], function (err, result) {
    if (err) throw err;

    var response = {
      "statusCode": 200,
      "headers": {
        "Content-Type": "application/json"
      },
      "body": JSON.stringify(result),
      "isBase64Encoded": false
    };
    callback(null, response)
  });
};

As you can see, I am using ?如您所见,我正在使用? to apply the SQL Injection protection.应用 SQL 注入保护。 But I also noticed that doing something like this will give the protection但我也注意到做这样的事情会提供保护

var sql    = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);

Which way is used to protect the code from SQL Injections?哪种方式用于保护代码免受 SQL 注入? The way I used or the connetion.escape() way?我使用的方式还是connetion.escape()方式? Or some other way?还是其他方式?

Using ?使用? placeholders is simpler to read and write and is likely to offer increased performance, since the parameters can be encoded more efficiently (eg numbers could be sent over the wire as their binary representations, not as strings).占位符更易于读取和写入,并且可能提供更高的性能,因为可以更有效地编码参数(例如,数字可以作为二进制表示形式通过网络发送,而不是作为字符串发送)。

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

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