I am trying to view a data from Mysql and pass it to the profile page where i can see the info of the user but i tried many time and different ways but couldnt find a way and also there is no errors I used {{#each}}{{this.fullname}}{{/each}} i tired if also but the data does not display would anyone help me to pls to solve it or if there is another way to display my data
i am using node js, express and hbs engine
router.get('/profilePage/:userid', function(req, res) {
var userid = req.params.userid;
pool.query('SELECT * from users where id = ?', userid, function(error, results, feilds) {
if (error) {
console.log("error ocurred while getting user details of " + userid, error);
res.send({
"code": 400,
"failed": "error ocurred"
});
} else {
res.render("profilePage",{user:results});
}
});
});
Try this:
router.get('/profilePage/:userid', function(req, res) {
var userid = req.params.userid;
if (!userid) {
//No user id provided
} else {
pool.query('SELECT * from users where id = ?',
[userid],
(error, results, feilds)=> {
if (error) {
console.log("error ocurred while getting user details of " + userid, error);
res.send({
"code": 400,
"failed": "error ocurred"
});
} else {
if (results.length > 0) {
const profile = results[0]
//You can then access the user id with
console.log(profile.id)
res.render("profilePage",{user:profile});
} else {
console.log('unable to retrieve a profile')
}
}
});
}
});
Related
router.get('/profilePage/:userid', function(req, res) {
var userid = req.session.user
console.log(userid)
if (!userid) {
//No user id provided
} else {
pool.query('SELECT * from users where id = ?',
[userid],
(error, results, feilds)=> {
if (error) {
console.log("error ocurred while getting user details of " + userid, error);
res.send({
"code": 400,
"failed": "error ocurred"
});
} else {
if (results.length > 0) {
const profile = results[0]
//You can then access the user id with
console.log(profile.fullname)
res.render("profilePage",{profile});
} else {
console.log('unable to retrieve a profile')
}
}
});
}
});
how can I make the userid = logged-in user? I tried many ways such as sessions (var userid = req.session.user) but all did not work what is the correct way to make the userid = to logged-in user id?
i have user mysql table with users how to get user exists.
i check user using select user from where access token = .
and check result in node.js server.
app.post("/checkStatusUser", function (request, responce) {
var accessTokenCheck = request.body.accessToken;
console.log(accessTokenCheck);
con.query(
"SELECT * FROM user_token_individual WHERE user_access_token = ?",
[accessTokenCheck],
function (err, res) {
if (err) {
responce.json({
STATUS_CODES: 404,
});
console.log(404);
responce.end();
} else {
if (!res.lenght) {
console.log(res);
responce.json({
STATUS_CODES: 200,
});
console.log(200);
responce.end();
}
console.log(404);
responce.end();
}
}
);
});
I don’t understand how to check if there is a user with such a token.
in res i have two log 200 and 404 because why i dont understand
I'd suggest using the response.status function to indicate status to the user, you can then use response.json to indicate the message. You could also use response.sendStatus if you just want to send text status, this would append a message to the response.
I'd suggest using a 500 status code in the case of an error, this indicates something we didn't expect, this is up to you of course!!
So something like this should work:
app.post("/checkStatusUser", function (request, responce) {
var accessTokenCheck = request.body.accessToken;
console.log(accessTokenCheck);
con.query(
"SELECT * FROM user_token_individual WHERE user_access_token = ?",
[accessTokenCheck],
function (err, res) {
if (err) {
console.error("An error occurred:", err.message);
responce.status(500).json({ status: 500, message: "An error occurred: " + err.message });
} else {
if (res.length) {
console.log( "User found successfully.");
responce.status(200).json({ status: 200, message: "User found successfully." });
} else {
console.log( "User not found.");
responce.status(404).send({ status: 404, message: "User not found." });
}
}
}
)
});
I have made a login system where i am logging in using mobile number and password.Before my code was showing welcome back 03**** ** because i had used request.session.number. I have changed the code so that i can get first name from the database whether employer or helper login.But it is not working.It is showing welcome back, undefined. I am unable to get the name from database.Can anyone tell me how to get it or where i am wrong. I will be thankful if anyone can help me in this regard.
app.post('/auth', function(request, response) {
var number = request.body.number;
var password = request.body.pwd;
if (number && password) {
var sql = `SELECT fyp_helpers.Mobile_number AS number,fyp_helpers.Password AS Password FROM fyp_helpers WHERE Mobile_number = ? UNION SELECT
fyp_employers.Employer_Contact AS number , fyp_employers.Employer_Password AS Employer_Password FROM fyp_employers
WHERE Employer_Contact = ?`;
connection.query(sql, [number, number], function (error, results, fields) {
if (results.length > 0) {
var hashedPassword = results[0].Password;
bcrypt.compare(password, hashedPassword, function (cryptErr, cryptResult) {
if (cryptResult) {
request.session.loggedin = true;
request.session.number = number;
var name= connection.query(`select fyp_helpers.First_Name As name FROM fyp_helpers UNION select fyp_employers.Employer_Fname As name FROM fyp_employers`,[name,name],function(error, results, fields)
{
if(!err)
console.log(name);
else
console.log(error);
})
response.redirect('/home');
} else {
response.send('Incorrect Password!');
console.log(cryptErr);
}
response.end();
});
} else {
response.send('User not registered');
}
});
}
else {
response.send('Please enter Username and Password!');
response.end();
}
});
app.get('/home', function(request, response) {
if (request.session.loggedin) {
response.send('Welcome back, ' + request.session.name + '!');
} else {
response.send('Please login to view this page!');
}
response.end();
});
app.listen(3000);
Everything is working fine but the only problem is it is not getting name.
Edit
var name= connection.query(`select fyp_helpers.First_Name As name FROM fyp_helpers UNION select fyp_employers.Employer_Fname As name FROM fyp_employers`,[name,name],function(error, results, fields)
{
if(!error) {
request.session.name = name;
console.log(name);
}
else
console.log(error);
})
I have declared name to session but it is still not working.Do i place it on wrong position or my query is not right to select the name?
You forgot to add name in request.session.name. Variable name is fetched but not used.
I am implementing registration API, in this registration, I have email as unique and I want to check if email exists or not in db if exists it has to show email already exists message else it has to register.everything works fine up to this.Now I want to check if an email does not exist in the database it has to show user not found the error but I am not able to display this message.
Here is my code
createUser: function(req, res, next) {
UserModel.getByEmail(req.body.email,function(err, user) {
if(err) {
res.json({ 'valid': false, 'message': err.message });
} else {
if(!user) {
res.json({ 'valid': false, 'message': 'User not exists'}); //this message is not showing
} else {
if(user[0].id) {
console.log('hi');
res.json({ 'valid': false, 'message': 'Email already exists'});//works only if i use user[0].id instead of user
} else {
UserModel.addUser(req, token, function(err, data) {
//console.log(data);
if (err) {
res.json({ 'valid': false, 'message': err.message });
} else {
console.log('Message sent: ' + info.response);
res.json({Error: info.response});
res.json({ 'valid': true, 'message': 'User added succesfully', req:req.body, data : data });
}
});
}
}
}
});},
In getByEmail method
getByEmail: function(email, rows){
var sql = "SELECT * FROM sbt_users WHERE email = ?";
var fields = [email];
return db.query(sql, fields, rows);}
if(!user) is not working.Can anyone explain how to show that message.
user is an array of records. If the array is empty, it's length will be 0.
So you can check if (user.length === 0)
I'm new in making API. I use Node.js and MySQL.
The fact is I have two GET function to get all users and one to get user by ID.
Both function are working when they are alone implemented. If both of them are implemented the function to get all user try to enter in the function to get user by ID so the API crash.
So here is my model users.js
var connection = require("../connection");
function Users()
{
//GET ALL USERS
this.get = function(res)
{
console.log('Request without id');
connection.acquire(function(err, con)
{
con.query('SELECT * FROM users', function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to get users'})
else
res.send(result);
});
});
}
//GET USER BY ID
this.get = function(id, res)
{
console.log('Request with ID');
connection.acquire(function(err, con)
{
if (id != null)
{
con.query('SELECT * FROM users WHERE id = ?', id, function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to find user: ' + id});
else if (result == "")
res.send({status: 1, message: 'Failed to find user: ' + id});
else
res.send(result);
});
}
});
}
And here is the routes.js
var users = require('./models/users');
module.exports = {
configure: function(app) {
app.get('/users/', function(req, res) {
users.get(res);
});
app.get('/users/:id/', function(req, res) {
users.get(req.params.id, res);
});
Do you have any idea why ?
Thanks for help :)
You can't have two functions with the same name in the same scope.
You have to rename your functions
/**
* Get all users
*/
this.get = function(res) {...}
/**
* Get user by id
*/
this.getById = function(id, res) {...}
Or you can have one function and check if an id is provided
this.get = function(id, res) {
if ( Number.isInteger(id) ) {
// return the user
} else {
res = id;
// return all users
}
}