防止 Nodejs MySQL SQL 注入 [英] Preventing Nodejs MySQL SQL Injection
本文介绍了防止 Nodejs MySQL SQL 注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何防止 NodeJS 的 SQL 注入?我正在尝试使用 ?符号和 req.param.但我无法上班.我应该如何正确使用 req.param.id?非常感谢.
How do I prevent SQL injection for NodeJS? I am trying to prevent SQL Injection using the ? symbol and the req.param. But I am not able to get to work. How should I use the req.param.id correctly? Many thanks in advance.
app.get('/products/:id', (req, res) => {
conn.getConnection(function (err, connection) {
if (err) throw err;
const SELECT_WHERE_PRODUCT_ID_QUERY = `SELECT * FROM products WHERE id = ?, $[req.param.id]`
connection.query(SELECT_WHERE_PRODUCT_ID_QUERY, function (error, results, fields) {
connection.release()
if (error) throw error;
return res.send(results)
});
});
});
推荐答案
是的,我们应该为此使用准备好的语句和 ?
作为占位符.为了使它工作,我们应该将参数作为单独的参数传递:
Yes, we should use prepared statements for that and ?
as placeholders. In order to make it work, we should pass parameters as a separate argument:
const query = 'SELECT * FROM products WHERE id = ?';
const params = [req.param.id];
connection.query(query, params, function (error, results, fields) {
另一种形式:
connection.query(
{
sql: 'SELECT * FROM products WHERE id = ?',
values: [req.param.id]
},
function (error, results, fields) {
有关更多示例,请参阅文档.
See documentation for more examples.
这篇关于防止 Nodejs MySQL SQL 注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文