I’m working on my middleware AuthController.js below. The middleware is part of a CRUD app. I created exports.create
which when requested will collect the first name and last name from the CRUD form. Once collected the MySql INSERT
query, will insert the data on the MySql user
table which is working fine.
What I cannot achieve and I need help is that together with the first name and last name info I want to insert also the variable { user_id: decoded.id }
, decoded.id
is a variable which take the user_id
value from another MySql table called login
.
When I request export.create
the following error shows on the terminal:
(node:18780) UnhandledPromiseRejectionWarning: TypeError: argument callback must be a function when provided
Basically I want that the value under user_id
column from the login
table is transferred to the user_id
column on user
table. Thank for any help.
exports.create = async (req, res, next) => { if (req.cookies.jwt) { try { //1)verify the token var decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET ); // console.log(decoded); const { first_name, last_name } = req.body; connection.query('INSERT INTO user SET first_name = ?,last_name = ?', { user_id: decoded.id }, [first_name, last_name,], (err, rows) => { if (!err) { res.render('add-crew', { alert: 'Crew member added succesfully!' }); } else { console.log(err); } console.log('The data from user table:n', rows); }); } catch (error) { console.log(error); return next(); } } };
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The connection.query
function takes in two to three arguments: the SQL statement, (the values) and the callback. Here, the function is taking four arguments, so it thinks [first_name, last_name,]
is the callback.
What you can do is:
...
connection.query('INSERT INTO user SET user_id = ?, first_name = ?,last_name = ?', [decoded.id, first_name, last_name,], (err, rows) => {
if (!err) {
res.render('add-crew', { alert: 'Crew member added succesfully!' });
} else {
console.log(err);
}
console.log('The data from user table:n', rows);
});
...
I hope this is what you are looking for.
Edit you could also do:
...
connection.query('INSERT INTO user SET ?', {user_id: decoded.id, first_name: first_name, last_name: last_name}, (err, rows) => {
if (!err) {
res.render('add-crew', { alert: 'Crew member added succesfully!' });
} else {
console.log(err);
}
console.log('The data from user table:n', rows);
});
...
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0