node.js mysql防注入,如何防止使用Node.JS进行SQL注入?

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);

});

ZG2qi.png

解决方案

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 :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值