the latest nodejs LTS version and MySQL package.
I wrote a module like the following:
[..]
getUserById: (userid) => {
return new Promise((resolve, reject) => {
db.getConnection((err, connection) => {
if (err) {
return reject(err);
}
let sql = 'SELECT * FROM users WHERE userid = ?';
let param = [userid];
sql = mysql.format(sql, param);
connection.query(sql, (err, rows) => {
if (err) {
return reject(err);
}
resolve(rows);
connection.release();
});
});
});
}
[..]
and calling it in route file:
[..]
const User = require('../models/user_model').CustomQueries;
router.get('/users/:userid', (req, res, next) => {
User
.getUserById(req.params.userid)
.then((rows) => {
if (rows.length === 0) {
res.json({ message: 'No user found.' });
}
res.status(200).json(rows);
})
.catch((err) => {
res.json(err);
});
});
When i try to get users with invalid userid i always get a warning
(node:7809) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:7809) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.Did i write a wrong Promise?
Yes. Just remove the .status(200) part
Oh, I see, you're calling res.json twice
Обсуждают сегодня