How can I prevent SQL injection with Node.JS?

房东的猫 提交于 2019-12-12 15:18:36

问题


How could I select a row of MS SQL server database with Node.JS with preventing SQL injection? I use the express framework and the package mssql.

Here is a part of my code I use now with a possibility to SQL injection written in ES 6.

const express = require('express'),
      app = express(),
      sql = require('mssql'),
      config = require('./config');

let connect = (f, next) => {
    sql.connect(config.database.connectionstring).then(f).catch((err) => {
        next(err);
    });
};

app.get('/locations/get/:id', (req, res, next) => {
    let f = () => {
        new sql.Request().query(`select * from mytable where id = ${req.params.id}`)
                         .then((recordset) => {
            console.dir(recordset);
        }).catch((err) => {
            next(err);
        });
    };

    connect(f, next);
});


回答1:


Use a PreparedStatement. Here is how you do it from the docs https://www.npmjs.com/package/mssql#prepared-statement :

var ps = new sql.PreparedStatement(/* [connection] */);
ps.input('id', sql.Int);
ps.prepare('select * from mytable where id = @id', function(err) {
  ps.execute({id: req.params.id}, function(err, recordset) {
    ps.unprepare(function(err) {
        // ... error checks 
    });

    // Handle the recordset
  });
});

Remember that each prepared statement means one reserved connection from the pool. Don't forget to unprepare a prepared statement!

You can also create prepared statements in transactions (new sql.PreparedStatement(transaction)), but keep in mind you can't execute other requests in the transaction until you call unprepare.

The docs are written in ES5 but I', sure you can Promisify it :)



来源:https://stackoverflow.com/questions/41742200/how-can-i-prevent-sql-injection-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!