Always getting 'Server is not responding!!' error in Node express - node.js

While calling the service layer from the controller, the response is not waiting for the result in the controller.
So, I am not getting correct response (return value) from the service layer.
controller =>
const { serviceCreateData } = require("../services/data.servises");
module.exports.createData = async (req, res) => {
try {
const result = await serviceCreateData(req.body);
if (result) {
res.status(result.status).json({ message: result.msg });
}
} catch (error) {
res.status(500).json({ message: "Server is not responding!!" });
}
};
Service layer
/** #format */
const dataModel = require("../models/data.model");
module.exports.serviceCreateData = async (insertedData) => {
const { name, email, username, phone, address } = insertedData;
try {
dataModel.findOne({ email }).exec(async (error, user) => {
if (user) {
return { success: false, status: 400, msg: "Data already exist!!" };
} else {
const _data = new dataModel({
name,
email,
username,
phone,
address,
});
await _data.save((error, data) => {
if (error) {
return {
success: false,
status: 400,
msg: "Something went wrong!!",
};
}
if (data) {
return {
success: true,
status: 201,
body: "Data inserted successfully!!",
};
}
});
}
});
} catch (error) {
return { success: false, status: 400, msg: "Something went wrong!!" };
}
};
I need to return the value from the services layer to controller, so that I can send it to the client.
Right now I am getting error responses from the controller only.
All the help is appreciated.

Related

2fa is not working on live server in nodejs

I am trying to implement 2fa using the otplib package and it's working fine on the local machine but not on the live server.
Can somebody help me?
on live, I am getting an invalid 2FA.
Here is the code:
exports.enableTwoFactorAuthentication = async (req, res) => {
try {
let data = req.body;
console.log("data: ", data)
const { userId, one_time_password } = data;
const user = await CRMUser.findById(userId);
const { tfa_auth_secret_key } = user;
console.log('user', tfa_auth_secret_key, user)
console.log("authenticator.check(one_time_password, tfa_auth_secret_key): ",authenticator.check(one_time_password, tfa_auth_secret_key))
if (!one_time_password || !authenticator.check(one_time_password, tfa_auth_secret_key)) {
return res.status(200).send({ success: false, message: 'Invalid 2FA Code.'});
}
else {
user.tfa_auth_status = true;
await user.save();
return res.status(200).json({ success: true, message: '2FA enabled successfully.', tfa_auth_status: true, secretKey: user.tfa_auth_secret_key, qrImage: user.tfa_auth_qr_image });
}
} catch (error) {
return res.status(500).json({ success: false, message: error.message })
}
};

Node.js Mongoose Login with bcrypt

So, I'm creating a login functionality using Mongoose with Node.js. Where I'm getting error while inserting wrong password.
Here is the error which I'm getting in response:
status: 0,
msgCode: 421,
message: error,
responseData: {}
I don't know why but I'm not getting proper error for Wrong Password situation which is
status: 0,
msgCode: 420,
message: 'Invalid credentials',
responseData: {}
Here is my code :
Controller :
module.exports.login = (req, res) => {
var user = {
email: req.body.email,
password: req.body.password
};
var rules = {
email: 'required|email',
password: 'required'
};
Validator(user, rules, {}, (err, status) => {
if (!status) {
res.json({
status: 0,
msgCode: 412,
message: 'Validation failed',
responseData: err
});
} else {
userModel.login(user).then(dbResponse => {
if (dbResponse.email != null) {
jwt.sign(user, key.secret, { expiresIn: 600000 }, (error, token) => {
if (error) {
res.json({
status: 0,
msgCode: 418,
message: error,
responseData: {}
});
}
else {
res.status(200).json({
status: 1,
message: 'Login successful',
responseData: { token: token, userData: dbResponse }
});
}
});
} else {
res.json({
status: 0,
msgCode: 420,
message: 'Invalid credentials',
responseData: {}
});
}
}).catch((error) => {
res.json({
status: 0,
msgCode: 421,
message: error,
responseData: {}
});
});
}
});
}
Model :
module.exports.login = (user) => {
return new Promise((resolve, reject) => {
userModel.findOne({ email: user.email }, (error, row) => {
if (row) {
if ( bcrypt.compareSync(user.password, row.password) ) {
resolve(row);
} else {
reject(error);
}
} else {
reject(error);
}
});
});
}
Please help. Thanks
As the answer from Lzok already said, because you reject the promise if the password mismatch in the userModel.login(user) function, the catch block will be always executed and the execution will never reach the res.json statement with msgCode 420
The fast solution is to modify the login function like this:
module.exports.login = (user) => {
return new Promise((resolve, reject) => {
userModel.findOne({ email: user.email }, (error, row) => {
if (row) {
if ( bcrypt.compareSync(user.password, row.password) ) {
resolve(row);
} else {
resolve({ email: null });
}
} else {
reject(error);
}
});
});
}
But it would be better to resolve with an undefined:
module.exports.login = (user) => {
return new Promise((resolve, reject) => {
userModel.findOne({ email: user.email }, (error, row) => {
if (row) {
if ( bcrypt.compareSync(user.password, row.password) ) {
resolve(row);
} else {
resolve(undefined);
}
} else {
reject(error);
}
});
});
}
And to update your if statement in the then block:
if (dbResponse !== undefined && dbResponse.email !== null) {
jwt.sign(user, key.secret, { expiresIn: 600000 }, (error, token) => {
if (error) {
That is because this line userModel.login(user).then(...).catch(...) is catching the error from the login method of your model. It does not matter which reject, both are captured in this catch.
Maybe you can use a type error there and check it in the original catch, something like:
userModel.login(user).then(...).catch((error) => {
if (error.type === 'invalid_credentials') {
res.json({
status: 0,
msgCode: 420,
message: 'Invalid credentials',
responseData: {}
});
}
// Maybe another handles you want here. Or return the default error
res.json({
status: 0,
msgCode: 421,
message: error,
responseData: {}
});
});

NextJs - Function in API folder in pages gives 'res.status is not a function' error

I'm using NextJs and I'm trying to create a subscription form that sends data to MailChimp. However, I'm getting error which says
res.status is not a function
This file is inside my pages/api directory. What might be going wrong?
import { subscribe } from "../../lib/api";
const request = require("request");
export default async function subscribeWithEmail(req, res) {
const { email, js } = req.body;
const mcData = {
members: [
{
email_address: email,
status: "pending",
},
],
};
const mcDataPost = JSON.stringify(mcData);
const options = {
url: "https://us6.api.mailchimp.com/3.0/lists/SECRET",
method: "POST",
headers: {
Authorization: "auth APIKEY",
},
body: mcDataPost,
};
if (email) {
request(options, (err, res, body) => {
console.log(res);
if (err) {
res.json({ error: err });
} else {
if (js) {
res.status(200).send({ message: "yay" });
} else {
res.redirect("/");
}
}
});
} else {
res.status(404).send({ message: "Failed" });
}
// res.status(200).json(data);
return res.status(200);
}
You are shadowing your initial res variable.
// you have another res here, which has nothing to do with Next.js res, but it is overriding it
// So you need to rename it to something else, for example to "response"
request(options, (err, response, body) => {
console.log(response);
if (err) {
res.json({ error: err });
} else {
if (js) {
res.status(200).send({ message: "yay" });
} else {
res.redirect("/");
}
}
});

Express async route logging undefined after await

I am writing an Express endpoint in Typescript to update a user's password in the database, but having some trouble with multiple queries/synchronous code.
My problem is right now I am trying to await the return of a function but it doesn't seem to be awaiting.
My route looks like this:
router.put("/:userId", validateUser, async (req: any, res: Response) => {
const result: any = await updatePassword(req.body.password, req.body.confirmPassword, req.params.userId);
console.log(result) //LOGS UNDEFINED????
if (result.status !== 200) res.status(result.status).send({ message: result.message, code: result.code });
res.send("Success!");
});
and that updatePassword function looks like this:
const updatePassword = async (password: string, confirmPassword: string, userId: string) => {
if (password !== confirmPassword) {
return { status: 409, message: Errors.mismatchingPasswordMessage, code: Errors.mismatchingPasswordCode };
}
const hashedPassword = bcrypt.hashSync(password, 10);
//update the password in the DB
pool.query("UPDATE users SET password = ? WHERE userId = ?", [hashedPassword, userId], (err: MysqlError, result: any) => {
if (err) {
console.log(err);
return { status: 500, message: err.message, code: err.code };
}
if (result.changedRows !== 1) {
return { status: 500, message: "Password could not be updated!" };
}
return { status: 200 };
});
}
Why is this the route not correctly awaiting the result of updatePassword??
Thanks in advance for any help.
The problem is, you're mixing async/await and callback style in this part
pool.query("UPDATE users SET password = ? WHERE userId = ?", [hashedPassword, userId], (err: MysqlError, result: any) => {
if (err) {
console.log(err);
return { status: 500, message: err.message, code: err.code };
}
if (result.changedRows !== 1) {
return { status: 500, message: "Password could not be updated!" };
}
return { status: 200 };
});
The function updatePassword jumps directly to the next line after this block, which is nothing. So it returns undefined.
You need to replace this block with async/await code. Something like :
try {
const result = await pool.query("UPDATE users SET password = ? WHERE userId = ?", [hashedPassword, userId]);
if (result.changedRows !== 1) {
return { status: 500, message: "Password could not be updated!" };
}
return { status: 200 };
}
catch (err){
console.log(err);
return { status: 500, message: err.message, code: err.code };
}

MongoDB Update field data

How can i used db.findAndUpdate table user and change my balance from previous amount to newer?
i have try to get balance and the result it show nothing, now i'm confuse to write in findAndUpdate. here's my code:
api:
app.post('/api/account/transfer', (req, res, next) => {
const { body } = req;
const {
sender,
receiver,
amount,
user,
balance,
} = body;
if (!sender) {
return res.send({
success: false,
message: 'Error: Sender cannot be blank!'
});
}
if (!receiver) {
return res.send({
success: false,
message: 'Error: Receiver cannot be blank!'
});
}
if (!amount) {
return res.send({
success: false,
message: 'Error: Fill Amount!'
});
} else if(balance < amount || balance == 0) {
return res.send({
success: false,
message: 'Insufficient funds!'
});
}
//save the new transaction
const newTransaction = new Transaction();
newTransaction.sender = sender;
newTransaction.receiver = receiver;
newTransaction.amount = amount;
newTransaction.save( (err, transaction) => {
if(err) {
return res.send({
success: false,
message: 'Error: Server error.'
});
}else{
return res.send({
success: true,
message: 'Transfer Success!'
});
}
});
//update user balance
User.findOneAndUpdate({
});
and here's the screenshoot:
so what i want is, if i'm as a receiver my balance will be increase.
Try this, the findOneAndUpdate operation does not wait for save operation to complete.
app.post('/api/account/transfer', (req, res, next) => {
const {
body
} = req;
const fields = ['sender', 'receiver', 'amount', 'balance'];
fields.forEach((field) => {
if (!body[field]) {
return res.send({
success: false,
message: 'Error: ' + field + ' cannot be blank!'
});
}
})
if (body.balance < body.amount || body.balance == 0) {
return res.send({
success: false,
message: 'Insufficient funds!'
});
}
//save the new transaction
let newTransaction = new Transaction();
// newTransaction = Object.assign(newTransaction, body); // If you want to copy all params from body to newTransaction
newTransaction.sender = body.sender;
newTransaction.receiver = body.receiver;
newTransaction.amount = body.amount;
newTransaction.save((err, transaction) => {
if (err) {
return res.send({
success: false,
message: 'Error: Server error.'
});
} else {
//update user balance
User.findOneAndUpdate({
/*query*/
}, {
/*body*/
}, (err, data) => {
if (err)
return res.send({
success: false,
message: 'Error: Server error.'
});
return res.send({
success: true,
message: 'Transfer Success!'
});
});
}
});
});

Resources