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." });
}
}
}
)
});
Related
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')
}
}
});
}
});
I am using postman with nodejs and MySQL.
Middleware
const notFound = (req, res, next) => {
const error = new Error(`Not Found -${req.originalUrl}`);
res.status(404);
next(error);
};
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? null : err.stack,
});
};
export { notFound, errorHandler };
here I am trying to use notFound and errorHandler for the authUser
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
let sql =
"select #uid :=`user_id`, first_name, last_name, email from dasa_user as var, (SELECT #uid := NULL) init_var where email=?;select #finaluid:= `user_id` from user_type, (SELECT #finaluid := NULL) init_var where user_id =#uid AND type='customer';select customer_id, password from customer where user_id =#finaluid;";
db.query(sql, [email], (err, result) => {
if (err) throw err;
if (result) {
if (result[2][0] == null) {
res.status(401);
throw new Error("user not Found");
} else {
if (MatchPassword(password, result[2]["0"]["password"])) {
res.json({
first_name: result[0][0]["first_name"],
last_name: result[0][0]["last_name"],
email: result[0][0]["email"],
userId: result[1]["0"]["#finaluid:= `user_id`"],
customerId: result[2]["0"]["customer_id"],
password: result[2]["0"]["password"],
token: generateToken(result[0][0]["email"]),
});
} else {
res.status(401);
throw new Error("Invalid email or password");
}
}
} else {
res.status(401);
throw new Error("Invalid email or password");
}
});
});
Now for this particular controller, I am accessing api/users/signin which is valid. But When I use something like api/users/signin/ksds. It does use notFound middleware and gives me error in postman. But in body If I use incorrect password, it should show error in postman console. But what it does it gives me error in vscode console. like this,
And I have to refresh the server everytime.
In order to access the notFoundanderrorHandler, I am using app.use` in server.js like this,
app.use(notFound);
app.use(errorHandler);
How can I solve this? So, that this will help me in showing error in the frontend too.
This errors comes in when you get empty results. You should first check the length of the results then use properties or index on it.
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
let sql =
"select #uid :=`user_id`, first_name, last_name, email from dasa_user as var, (SELECT #uid := NULL) init_var where email=?;select #finaluid:= `user_id` from user_type, (SELECT #finaluid := NULL) init_var where user_id =#uid AND type='customer';select customer_id, password from customer where user_id =#finaluid;";
db.query(sql, [email], (err, result) => {
try {
if (err) throw err;
if (result.length > 0) {
if (result[2][0] == null) {
res.status(401);
throw new Error("user not Found");
} else {
if (MatchPassword(password, result[2]["0"]["password"])) {
res.json({
first_name: result[0][0]["first_name"],
last_name: result[0][0]["last_name"],
email: result[0][0]["email"],
userId: result[1]["0"]["#finaluid:= `user_id`"],
customerId: result[2]["0"]["customer_id"],
password: result[2]["0"]["password"],
token: generateToken(result[0][0]["email"]),
});
} else {
res.status(401); // this else is calling up for (If you use incorrect password)
throw new Error("Invalid email or password");
}
}
} else {
res.status(401).send({message: 'Results not found'}); // change this to send error message to the frontend, you can really customise it based on your needs.
// throw new Error("Results not found"); // Now this error is thrown because you don't have results
}
} catch (error) {
console.error(e);
}
});
});
But When I use something like api/users/signin/ksds. It does use
notFound middleware and gives me error in postman.
Because you are creating a custom error and sending it to node default error handler which does the work for you and postman receives the error message.
But in body If I use incorrect password, it should show error in
postman console. But what it does it gives me error in vscode console
However, in this case your are throwing an error and it is doing its job and you see that error in the console. If you don't want this behaviour follow the same flow as used above.
Check for more details: How to handle errors in Node.js?
I am unable to get res.send() to work for all the callbacks, an idea I had was to move the return res.send({ error, success }); to a callback placed above but then it doesn't do the potential error/success messages for below.
I tried doing it a different way where I used a function like createUser() that used a callback to return an error/success message but also wasn't able to get it to work. Is there anything that can point me to how I can make this work properly?
A friend suggested using await and async callbacks, but when searching it I wasn't too familiar to understand how it properly works.
app.post('/create', function(req, res) {
// -- Default Variables
let error = "";
let success = "";
let formData = req.body.formData;
if (formData.userName, formData.userPass, formData.userEmail) {
console.log(formData);
conn.query("SELECT COUNT(userId) AS rowCount FROM users WHERE userName = ?", [formData.userName], function(error, results, fields) {
if (results[0].rowCount == 0) {
conn.query("INSERT INTO users ( userName, userEmail, userPass ) VALUES ( ?, ?, ? )", [ formData.userName, formData.userEmail, formData.userPass ], function(error, results, fields) {
if (results.affectedRows >= 1)
success = "Your account has successfully been created!";
else
error = "Unexpected error occured, please try again!";
});
} else { error = "You already have an account!"; }
});
} else {
error = "Please make sure all fields are entered correctly!";
}
// -- Return
return res.send({ error, success });
});
conn.query calls an async callback and return res.send({ error, success }); returns immediately. The values changed in the asynchonous callback are in a closure, that executes only after return res.send({ error, success }); already returned the value. So the only error that might show up is the only one in else branch.
Try rewriting it with promises:
app.post('/create', function x(req, res) {
return new Promise(function(resolve, reject){
let error = "";
let success = "";
let formData = req.body.formData;
if (formData.userName && formData.userPass && formData.userEmail) {
console.log(formData);
conn.query("SELECT COUNT(userId) AS rowCount FROM users WHERE userName = ?", [formData.userName], function(error, results, fields) {
if (results[0].rowCount == 0) {
conn.query("INSERT INTO users ( userName, userEmail, userPass ) VALUES ( ?, ?, ? )", [ formData.userName, formData.userEmail, formData.userPass ], function(error, results, fields) {
if (results.affectedRows >= 1)
success = "Your account has successfully been created!";
else
error = "Unexpected error occured, please try again!";
resolve({ error, success });
});
} else {
error = "You already have an account!";
resolve({ error, success }); }
});
}
else{
error = "Please make sure all fields are entered correctly!";
resolve({ error, success });
}
});
});
Even though I know that always resolving is not a clean way to use Promises. You should consider changing your API return proper errors with appropriate HTTP error codes to client.
I can see multiple issues with your code:
It's actually working, BUT it's logically incorrect, returning your empty error and success variables immediately, without waiting for your queries to finish.
You have some conflict with your error variable, consider renaming to something that doesn't overlap with your outside declaration. While it does work, it gives you room for confusion.
Your if has incorrect conditions and logical operators.
Here's a quick fix, but not considering that this can be much much cleaner. Also some quick tips:
Return/Terminate early if possible.
Avoid very long lines to make your code much easier to read
app.post('/create', function(req, res) {
// -- Default Variables
let error = "";
let success = "";
const formData = req.body.formData;
const {
username,
userPass,
userEmail
} = formData;
// Avoid too much nested code, terminate/Return early if possible.
if (!userName || !userPass || !userEmail) {
error = "Please make sure all fields are entered correctly!";
return res.send({ error, success });
}
conn.query("SELECT COUNT(userId) AS rowCount FROM users WHERE userName = ?", [userName], function(error, results, fields) {
if (results[0].rowCount == 0) {
const parameters = [ userName, userEmail, userPass ];
// Avoid very long lines. It becomes harder to read (TIP: Consider using lint)
conn.query("INSERT INTO users ( userName, userEmail, userPass ) VALUES ( ?, ?, ? )", parameters , function(error, results, fields) {
if (results.affectedRows >= 1) {
success = "Your account has successfully been created!";
} else {
error = "Unexpected error occurred, please try again!";
}
res.send({ error, success }); return;
});
} else {
error = "You already have an account!";
res.send({ error, success }); return;
}
});
});
While trying to query a local MySQL database, I encounter the following error:
..\server\node_modules\mysql\lib\protocol\Parser.js:80
throw err; // Rethrow non-MySQL errors
^
Incorrect arguments
No further information is provided after that.
I've looked up the already available solutions such as adding:
con.on('error', function(err) {
console.log("[mysql error]",err);
});
or even replacing (the only) throw err in the code with console.log(err); but none did the trick.
The server eventually crashes once the error is displayed, and it happens after the console.log('Query res: ', results); in the code below, meaning that the request has been successful and has fetched the wanted data.
As I see it, it could be caused by bcrypt, but the error comes from the MySQL node.js package as seen in the logs.
loginroutes.js:
exports.login = function(req, res) {
console.log("email:", req.body.email, "password:", req.body.password);
var email = req.body.email;
var password = req.body.password;
con.query("SELECT * FROM users WHERE email = ?", [email], (err, results) => {
if (err) {
console.log("Error ocurred");
res.send({"code":400, "failed":"error occurred"});
} else {
console.log('Query res: ', results);
if (results.length > 0) {
if (bcrypt.compareSync(results.password, password))
res.send({"code":200, "success":"login successful"});
else
res.send({"code":204, "success":"email & password combination does not match"});
} else
res.send({"code":204, "success":"email does not exist"});
}
});
};
What is it I missed and what can I do to solve that issue ?
Thank you.
EDIT: also tried with SELECT * FROM users WHERE email = \"" + email + "\"" just for the sake of it, it turns out similar to the previous request.
To log any exception in the code you need to put the code block inside try catch
try {
// your code here
} catch (error) {
console.log(error);
res.send({ code:400, failed: "error occurred"});
}
please try this code and paste error here.
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)