进行 mysql 查询的 NodeJS 路由不会传递查询中的每个参数



我有一个用于存储请求主体的变量,一个查询变量,然后我使用"conn.query"函数。下面是代码:

app.post('/register', async (req, res) => {
//get the request's body in a variable
const thebody = req.body;
//get connection
const conn = await pool.getConnection();
//create a new query
const query = 'INSERT INTO users (username, email, password) VALUES (?, ?, ?)';
//executing the query
const result = await conn.query(query, thebody.username, thebody.email, thebody.password);
res.status(200).json(result);
})

错误如下:

text: 'Parameter at position 2 is not set',
sql: "INSERT INTO users (username, email, password) VALUES (?, ?, ?) - parameters:['filou']",
fatal: false,
errno: 45016,
sqlState: 'HY000',
code: 'ER_MISSING_PARAMETER'
}

下面是通过postman发送的请求正文:

{
"username" : "filou",
"password" : "azerty",
"email" : "email.com"
}

我试图把thebody.username, thebody.email and thebody.password放在括号[…]但是我得到了另一个错误"不知道如何字符串化"。你们知道是怎么回事吗?

查询的第二个参数应该是一个带参数的数组,所以尝试这样做:conn.query(query, [thebody.username, thebody.email, thebody.password]);

最新更新