Im making an API on nodejs with express and mysql. In the POST method i dont get any error but on mysql store al values as 0, like this:
1
0
0.00
0000-00-00
0
(the 1 is the ID autoincremental)
To test the post method im using POSTMAN like this:
{
"Id" : null,
"Concepto" : "Desde POSTMAN",
"Monto" : 10,
"Fecha" : "1988-05-05",
"Tipo" : "Ingreso"
}
and this is the function
router.post('/', (req, res) => {
const { id,concepto,monto,fecha,tipo } = req.body;
mysqlConnection.query("INSERT INTO operaciones (Id, Concepto, Monto, fecha, Tipo) VALUES (?)", [req.body],(err, rows, fields) => {
if (!err) {
res.json({Status: "Operacion Saved"});
} else {
console.log(err);
}
});
});
Any advice, thanks
CodePudding user response:
Without seeing your table definition I assume that the DB engine is defaulting to the 0
values you're getting as the query is passing empty values.
You should be using ?
placeholders for each input you'd like to pass to the query.
Also, the deconstructed values aren't actually used.
Please try the following code:
router.post('/', (req, res) => {
const { id, Concepto, Monto, Fecha, Tipo } = req.body;
mysqlConnection.query("INSERT INTO operaciones (Concepto, Monto, Fecha, Tipo) VALUES (?, ?, ?, ?);", [Concepto, Monto, Fecha, Tipo], (err, results, fields) => {
if (!err) {
res.json({ Status: "Operacion Saved" });
} else {
console.log(err);
}
});
});
Notice id
isn't used in the query as you've mentioned it's set as auto-increment.