'how to pass a variable to REST API with NodeJS
I must use NodeJs to set different API routes to provide front-end functionalities. I have designed the server as : routes=> controller => models
The snippet code for the log in operations is:
server.js
const customerController = require('./customerController');
app.post('/api/managerSessions',customerController.login);
app.post('/api/customerSessions',customerController.login);
app.post('/api/supplierSessions',customerController.login);
app.post('/api/clerkSessions', customerController.login);
customerController.js
const customer = require('./admin_dao');
const passport = require('./passport');
exports.login = (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
console.log('user', user);
console.log('req.body', req.body)
if (err) {
return next(err);
}
if (!user) {
// display wrong login messages
return res.status(401).send(info);
}
// success, perform the login
req.login(user, (err) => {
if (err)
return next(err);
// req.user contains the authenticated user, we send all the user info back
// this is coming from userDao.getUser()
return res.json({ id: req.user.id, name: req.user.name, surname: req.user.surname });
});
})(req, res, next);
}
and the model is
exports.getUser = (username, password) => {
return new Promise((resolve, reject) => {
const query = 'SELECT id_customer as id,email, name, surname, password , type FROM customer WHERE email = ?';
db.get(query, [username], (err, row) => {
if (err)
reject(err); // DB error
else if (row === undefined)
resolve(undefined); // user not found
else {
bcrypt.compare(password, row.password).then(match => {
if (match) // password matches
resolve({ id: row.id, name: row.name, surname: row.surname, email: row.email, type: row.type });
else
resolve(false); // password not matching
});
}
});
});
}
As all those routes use the same table customer, I would like to use the type as variable in order to distinguish each route called at the login time because those routes use the same table describes as **customer(id_customer, name, surname, email, password, type)
**. For the moment I'm performing log in with only the username and it works
from now I would like to perform the login by taking the type of users as a parameter when calling the route propagating it to the controller and model such as I can perform the query 'SELECT id_customer as id,email, name, surname, password , type FROM customer WHERE email = ? and type=?'
; instead at the login times.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|