We are using Angular with Node.js Express.We try to update user details from settings page but when click the update button it throws:
Failed to load resource: net::ERR_CONNECTION_RESET It seems can't send an update through the observable. When I check this URL in Node: http://localhost:3000/api/chatapp/user/edit-user It says {"message":"No Authorization"} in the browser. Here is the code.
Angular
EditUser(body): Observable<any> {
return this.http.post(`${BASEURL}/user/edit-user`, body);
}
TS
private populateForm() {
const unusedFields = [
'_id',
...
...
];
const userInfo = Object.assign({}, this.user);
unusedFields.forEach((field) => delete userInfo[field]);
this.SettingsForm.setValue(userInfo);
}
private buildSettingsForm() {
this.SettingsForm = this.fb.group({
email: [null, [Validators.required, Validators.email], this.forbiddenEmails],
firstName: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
jobTitle: [null, [Validators.required]],
lastName: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
username: [null, [Validators.required, Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])')]]
});
this.SettingsForm.setValidators(this.minimumAge(18));
}
UpdateUser() {
this.usersService.EditUser(this.SettingsForm.value).subscribe(
data => {
console.log(data);
this.router.navigate(['main']);
},
err => console.log(err)
);
}
Also Node.js :
async EditUser(req, res,next) {
User.findById(req.user.id, function (err, user) {
if (!User) {
return res
.status(httpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'User is not found' });
}
const schema = Joi.object().keys({
username: Joi.string()
.min(4)
.max(10)
.required(),
email: Joi.string()
.email()
.required(),
firstName: Joi.string().required(),
lastName: Joi.string().required(),
jobTitle: Joi.string().required(),
});
const { error, value } = Joi.validate(req.body, schema);
if (error && error.details) {
return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details })
}
const email = Helpers.lowerCase(req.body.email);
const username = Helpers.lowerCase(req.body.username);
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const jobTitle = req.body.jobTitle;
User.email = email;
User.firstName = firstName;
User.lastName = lastName;
User.username = username;
User.jobTitle = jobTitle;
User.update()
});
}
}
Router
router.post('/user/edit-user', AuthHelper.VerifyToken, UserCtrl.EditUser);
MongoDb
const userSchema = mongoose.Schema({
username: { type: String },
email: { type: String },
isVerified: { type: Boolean, default: false },
password: { type: String },
passwordResetToken: String,
passwordResetExpires: Date,
firstName: { type: String },
lastName: { type: String },
jobTitle: { type: String },
...
...
module.exports = mongoose.model('User', userSchema);
I think something is wrong in both Node.js controller and in Angular function. What is wrong? How can we fix this error?
did you send the token with the request ?!
you've forget to construct the schema
const userSchema = new mongoose.Schema({
username: { type: String },
email: { type: String },
...
)}
to catch the error you might pass a callback as an argument to save function.
user.save(function (err, updatedUser) {
if (err) {
/* Handle the error */
};
});
you might use set user.set({ [key]: value });
instead of direct access by dot notation eg user.firstname
in your situation it will be like
user.set({
email: email,
firstName: firstName,
lastName: lastName,
username: username,
jobTitle: jobTitle
})
your final code will be
async EditUser(req, res, next) {
User.findById(req.user.id, function (err, user) {
if (!user) {
return res
.status(httpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'User is not found' });
}
const schema = Joi.object().keys({
username: Joi.string()
.min(4)
.max(10)
.required(),
email: Joi.string()
.email()
.required(),
firstName: Joi.string().required(),
lastName: Joi.string().required(),
jobTitle: Joi.string().required(),
});
const { error, value } = Joi.validate(req.body, schema);
if (error && error.details) {
return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details })
}
const email = Helpers.lowerCase(req.body.email);
const username = Helpers.lowerCase(req.body.username);
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const jobTitle = req.body.jobTitle;
user.set({
email: email,
firstName: firstName,
lastName: lastName,
username: username,
jobTitle: jobTitle
});
user.save(function (error, updatedUser) {
if (error) {
/* Handle it */
}
})
});
}
you can read more about in mongoose documents for more details
as note, in populateForm
method you can filter the object upon the unusedFields
array without use delete
keyword
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.