Axios.delete is not working the way I want it too - javascript

It's a gym app which when a user books themselves into a class, the class saves the userId as a user which will be attending, then also in the user model you also get the classes in which the user is attending too.
Currently hitting 500 (Internal Server Error).
These are the axios calls:
deleteClassHandler = () => {
this.deleteUserClassHandler();
const data = {
userId: this.props.userId,
classId: this.props.id
}
axios.delete('/api/classes/remove', data)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
deleteUserClassHandler = () => {
const data = {
userId: this.props.userId,
classId: this.props.id
}
axios.delete('/api/auth/remove', data)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
The this.props.userID and this.props.id are populated fine with the right values.
These are the routes -
Classes routes:
router.delete('/remove', ClassesController.deleteUser);
Auth routes:
router.delete('/remove', UserController.deleteClass);
This are the controllers:
Classes controller -
exports.deleteUser = (req, res) => {
console.log('cl userid ', req.body.userId);
console.log('cl classid ', req.body.classId);
GymClass.findById({
_id: req.body.classId
}, 'classMembers', (err) => {
if (err) {
console.log('class up here');
res.status(401).json({
message: "Error Occured!"
})
} else {
GymClass.findByIdAndDelete({
"classMembers.userId" : mongoose.Types.ObjectId(req.body.userId)
}, (err) => {
if(err) {
console.log('class down');
res.status(401).json({
message: "Error Occured!"
})
} else {
res.status(200).json({
message: "Success!"
})
}
});
}
})
}
Auth controller -
exports.deleteClass = (req, res) => {
console.log('auth userid', req.body.userId);
console.log('auth classid', req.body.classId);
User.findById({
_id: req.body.userId
}, 'bookedClasses', (err) => {
if (err) {
console.log('auth up here');
res.status(401).json({
message: "Error Occured!"
})
} else {
GymClass.findByIdAndDelete({
"bookedClasses.classId" : mongoose.Types.ObjectId(req.body.classId)
}, (err) => {
if(err) {
console.log('auth down here');
res.status(401).json({
message: "Error Occured!"
})
} else {
res.status(200).json({
message: "Success!"
})
}
});
}
})
}
I am by no means a backend superstar and I have hit a brick wall with this one, does anyone here know how I could maybe possibly change the code and the way I am tackling this? Any issues spotted? I have got a 500 server error and I am not sure what to do. I can always post the two models for the user and classes if needed.
This was also something I tried but did not work -
axios.delete('/api/classes/remove', {
data: {
userId: this.props.userId,
classId: this.props.id
}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}

Related

Problem with recording image name in SQL with Sequelize + multer

I'm trying to write a user image to a nodejs + sequelize + sqlServer server.
The first part of the function is to record the image to the server the complete one correctly.
But I can't save the filename in the img field of the database.
In postman gives me code 200 but then cool I make a get to the user not to record the filename in the field.
Thanks in advance.
app.put('/upload/:tipo/:idUsuario', upload.single('imagen'), (req, res) => {
try {
res.send(req.file);
const { tipo, idUsuario } = req.params;
usuariosModel.findOne({ where: { idUsuario: idUsuario } })
.then(updateimg => {
updateimg.update({ img: req.file.filename })
.then(() => {
res.status(200).send({ updateimg });
})
.catch(error => {
res.status(500).send({ msg: 'OcurriĆ³ un error al actualizar el usuario' });
})
})
.catch(error => {
console.log(error);
});
} catch (err) {
console.log(err);
}
});
user.js : model
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class user extends Model {
}
user.init({
name: { type: DataTypes.STRING, },
img: { type: DataTypes.STRING, },
}, {
sequelize,
modelName: "user",
defaultScope: {
attributes: { exclude: ["createdAt", "updatedAt"] }
}
});
return user;
};
router.js
router.put('/upload/:idUsuario', upload.single('imagen'), (req, res) => {
try {
// res.send(req.file); // must comment this
const { idUsuario } = req.params;
db.user.findOne({ where: { id: idUsuario } })
.then(updateimg => {
updateimg.update({ img: req.file.filename })
.then(() => {
res.status(200).send({ updateimg });
})
.catch(error => {
res.status(500).send({ msg: 'OcurriĆ³ un error al actualizar el usuario' });
})
})
.catch(error => {
console.log(error);
});
} catch (err) {
console.log(err);
}
});
https://github.com/nkhs/node-sequelize/blob/stack-66495393/api/routes/game.js
I tested this with post man
http://prntscr.com/10dt3jq
http://prntscr.com/10dt4o8

Not returning an error after failed post request - axios, express, node.js

I am trying to implement the validation of password change and the issue I have is that I am not getting errorMessage back from the server in case of an error. I have managed to get it work and send back response after the password was updated. Also, I can console.log the error message on the back end but it's not returning an object with errorMessage to the front end.
if (!currentPassword) {
console.log("no current password");
return res
.status(400)
.json({ errorMessage: "Please confirm your current password" });
}
On the front code looks like this:
handleSubmit = (event) => {
event.preventDefault();
const authorization = localStorage.getItem("accessToken");
axios
.put(
`${process.env.REACT_APP_SERVER_URL}/settings/password`,
this.state.user,
{
headers: {
authorization,
},
}
)
.then((res) => {
if (res.errorMessage) {
console.log(res, "Unsuccessful password updated");
} else {
console.log("updating - res:", res);
this.setState({
user: res.data,
});
}
})
.catch((err) => {
console.log(err, "ERROR");
});
};
Everytime there is an error, I am not consol login the actual erroMessage but it is being catched in catch. What is the cause of that?
Thanks
Not a direct res its available under res.data.
Response schema of axios
use
if (res.data.errorMessage) {
instead of
if (res.errorMessage) {
For better understanding you need to console.log(res). Then you could understand the structure of the response
router.put("/password", isLoggedIn, (req, res, next) => {
const { currentPassword, newPassword, newPasswordConfirm } = req.body;
User.findById(req.user._id)
.then((user) => {
bcrypt.compare(currentPassword, user.password).then((isSamePassword) => {
if (!isSamePassword) {
console.log(
"Incorrect current password. To change your password try again!"
);
return res.status(400).json({
errorMessage:
"Incorrect current password. To change your password try again!",
});
}
return bcrypt
.genSalt(saltRounds)
.then((salt) => bcrypt.hash(newPassword, salt))
.then((hashedPassword) => {
User.findByIdAndUpdate(
req.user._id,
{ password: hashedPassword },
{ new: true }
)
.then((user) => {
console.log("user's password successfully changed");
res.status(200).json(user);
})
.catch((err) => {
res.status(500).json({ errorMessage: err.message });
});
})
.catch((err) => {
res.status(500).json({ errorMessage: err.message });
});
});
})
.catch((err) => {
console.log(err);
res.status(500).json({ errorMessage: err.message });
});
});

How to call exports.function from exports.function in NodeJS?

I have a controller function that is declared like this. Based on my comment for this function, I need to call a DB method to get the currentUser data, but I want to re-use an exports.function for that.
I want to call this getme function:
// Get the profile of the current user through JWT.
exports.getme = (req, res) => {
db.User.findOne({
where: { id: req.user.id },
include: [
{
model: db.Role,
as: "role"
},
{
model: db.UserType,
as: "userType"
},
{
model: db.PushToken,
as: "pushToken"
},
{
model: db.StripeAccount,
as: "stripeAccount"
}
],
attributes: defaultAttributes
})
.then(data => {
res.send(data)
})
.catch(err => {
console.log(err)
res.status(500).send({
message: "An error has occured while retrieving data."
})
})
}
from this createStripeAccount function.
// Create Stripe Account
// If there's no stripeAccount connected to the current user,
// only then will we attempt to call stripe's create.
exports.createStripeAccount = (req, res) => {
stripe.accounts.create({
type: 'express',
country: 'US',
email: req.user.email
})
.then(account => {
console.log('Account: ', JSON.stringify(account))
stripe.accountLinks.create({
account: account.id,
refresh_url: 'https://app.com/reauth',
return_url: 'https://app.com/return',
type: 'account_onboarding',
})
.then(accountLinks => {
console.log('Account links: ', accountLinks.url)
return res.send(accountLinks)
})
.catch(err => {
console.log("Error fetching account links from Stripe: ", err.message);
return res.status(500).send({
message: err.message || "An error has occured while fetching account links from Stripe."
});
})
}).catch(err => {
console.log("Error creating Stripe account: ", err.message);
return res.status(500).send({
message: err.message || "An error has occured while creating Stripe account."
});
});
};
Define the function first, export it later.
function getme() {
// ...
}
function createStripeAccount() {
// ...
getme(...);
// ...
}
exports.getme = getme;
exports.createStripeAccount = createStripeAccount;
use this.getme(...) wherever you want to use inside createStripeAccount function.

RESTful API for HTTP DELETE doesnt check for null

Im currently writing a RESTful API for a webservice but im having trouble. Im trying to delete an mail, but first i want to check if the mail even exists. My problem is that it doesn't check if mail is null and doesn't respond with a 404. Im working with express and mongoose
router.delete('/:id', (req, res) => {
const { id } = req.params;
Mail.findById(id)
.exec()
.then((mail) => {
if (!mail) {
console.log(mail) // returns null
return res.status(404);
}
})
.then(
Mail.deleteOne({ _id: id })
.exec()
.then(() => {
res.status(200).json({
message: 'Mail deleted',
});
})
.catch((err) => {
res.status(500).json({ error: err });
})
);
});
I think you have to do the the deletion part of the code inside the first then block as an else statement. You are not returning anything that the next then block can use.
you could do:
Mail.findById(id)
.exec()
.then((mail) => {
if (!mail) {
console.log(mail) // returns null
return res.status(404).send() //need to send response;
}
Mail.deleteOne({ _id: id })
.exec()
.then(() => {
res.status(200).json({
message: 'Mail deleted',
});
})
}).catch((err) => {
res.status(500).json({ error: err });
})
PRO TIP: if you don't know it, learn async await. Code will look much cleaner!
Then it would look like this:
router.delete('/:id', async (req, res) => {
const { id } = req.params;
try {
const mail = await Mail.findById(id);
if(!mail) {
return res.status(404).send();
}
await Mail.deleteOne({_id: id});
res.status(200).json({
message: 'Mail deleted',
});
} catch(e) {
res.status(500).json({ error: err });
}

NodeJS - Cannot set Headers after they are sent to the client

So I've searched around and found out that to fix the said issue, I have to return after sending a response. But my problem is, even though I have return, I still have the error.
const dbEditCourse = (req, res, db, logger) => {
let {
origCourse, code, description, type
} = req.body;
if (!code || !description || !type) {
res.json({
haveEmpty: true
});
return;
}
db.transaction((trx) => {
db.select('*').from('course_strand').where('code', '=', code)
.then(data => {
if (data[0]) {
//error happens in this block of code
res.json({
isSuccess: false
});
return;
//i also tried return res.json({ isSuccess: false });
}
//wrapping this in 'else' also does not work
return db('course_strand')
.returning('*')
.where('code', '=', origCourse)
.update({ code, description, type })
})
.then(course => {
return db('activity_logs')
.returning('*')
.insert({
date: new Date(),
employee_id: req.session.emp_id,
module: "COURSE / STRAND",
activity: "EDIT"
})
})
.then(activity => {
if (activity[0]) {
res.json({
isSuccess: true
});
return;
} else {
res.json({
isSuccess: false
});
return;
}
})
.then(trx.commit)
.catch(err => {
logger.error(err);
trx.rollback;
res.render('pages/error-500');
});
})
.catch(err => logger.error(err));
}
module.exports = {
dbEditCourse
}
What I'm doing to produce the error is, If the record is existing, it will go into the block of code above. Aside from that specific block of code, I don't encounter the error elsewhere. And the code is working fine even though I have the error.
You cannot break a promise chain with return keyword, all .then statements will be executed (exclude you throw an error in a .then), the res.json has been called many times.
Handler all errors (include your error and system error) in catch block.
In catch block, check the error is throwing by you or not to return the response.
const dbEditCourse = (req, res, db, logger) => {
let {
origCourse, code, description, type
} = req.body;
if (!code || !description || !type) {
res.json({
haveEmpty: true
});
return;
}
// util throw a error
const breakWithMyError = () => {
throw new Error("MY_ERROR");
}
db.transaction((trx) => {
db.select('*').from('course_strand').where('code', '=', code)
.then(data => {
if (data[0]) {
//error happens in this block of code
breakWithMyError();
//i also tried return res.json({ isSuccess: false });
}
//wrapping this in 'else' also does not work
return db('course_strand')
.returning('*')
.where('code', '=', origCourse)
.update({ code, description, type })
})
.then(course => {
return db('activity_logs')
.returning('*')
.insert({
date: new Date(),
employee_id: req.session.emp_id,
module: "COURSE / STRAND",
activity: "EDIT"
})
})
.then(activity => {
// revert logic, we check for error case first
if (!activity[0]) {
breakWithMyError();
}
})
.then(trx.commit)
.then(() => {
// finally you can run to here without any error
res.json({
isSuccess: true
});
})
.catch(err => {
// If you any error, the error comes form `breakWithMyError` or any things.
if (err.message === "MY_ERROR") {
// the error throw by `breakWithMyError`
return res.json({
isSuccess: false
});
}
logger.error(err);
trx.rollback;
// Why you return a html page in failed case? `res.status(500).json({message: "Internal server!"});`
res.render('pages/error-500');
});
})
.catch(err => logger.error(err));
}
module.exports = {
dbEditCourse
}
const dbEditCourse = (req, res, db, logger) => {
let {
origCourse, code, description, type
} = req.body;
if (!(code && description && type)) {
res.json({
haveEmpty: true
});
return;
} else { // Please Try this.
db.transaction((trx) => {
db.select('*').from('course_strand').where('code', '=', code)
.then(data => {
if (data[0]) {
//error happens in this block of code
res.json({
isSuccess: false
});
return;
//i also tried return res.json({ isSuccess: false });
}
//wrapping this in 'else' also does not work
return db('course_strand')
.returning('*')
.where('code', '=', origCourse)
.update({ code, description, type });
})
.then(course => {
return db('activity_logs')
.returning('*')
.insert({
date: new Date(),
employee_id: req.session.emp_id,
module: "COURSE / STRAND",
activity: "EDIT"
});
})
.then(activity => {
if (activity[0]) {
res.json({
isSuccess: true
});
return;
} else {
res.json({
isSuccess: false
});
return;
}
})
.then(trx.commit)
.catch(err => {
logger.error(err);
trx.rollback;
res.render('pages/error-500');
});
})
.catch(err => logger.error(err));
}
};
module.exports = {
dbEditCourse
};

Categories