node預防sql注入的方法:
1.使用mysql.format()轉(zhuǎn)義參數(shù),例如:
var userId = 1;
var sql = "SELECT * FROM ?? WHERE ?? = ?";
var inserts = ['users', 'id', userId];
sql = mysql.format(sql, inserts); // SELECT * FROM users WHERE id = 1
2.使用connection.query()的查詢參數(shù)占位符,例如:
var userId = 1, name = 'test';
var query = connection.query('SELECT * FROM users WHERE id = ?, name = ?', [userId, name], function(err, results) {
// ...
});
console.log(query.sql); // SELECT * FROM users WHERE id = 1, name = 'test'
或者改寫成:
var post = {userId: 1, name: 'test'};
var query = connection.query('SELECT * FROM users WHERE ?', post, function(err, results) {
// ...
});
console.log(query.sql); // SELECT * FROM users WHERE id = 1, name = 'test'
3. 使用escapeId()編碼SQL查詢標識符,例如:
var sorter = 'date';
var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter);
connection.query(sql, function(err, results) {
// ...
});
4.使用escape()對傳入?yún)?shù)進行編碼,例如:
var userId = 1, name = 'test';
var query = connection.query('SELECT * FROM users WHERE id = ' + connection.escape(userId) + ', name = ' + connection.escape(name), function(err, results) {
// ...
});
console.log(query.sql); // SELECT * FROM users WHERE id = 1, name = 'test'