request not found error during post request - node.js

I have form with the following action
<form action="users/edit/profile/{{user._id}}" method="post">
route.js
router.post('/edit/profile/:id', controllers.updateUserProfile);
and in controller
updateUserProfile: function(req, res){
User.findByIdAndUpdate(req.params.id, { $set: { username: req.body.username, email: req.body.email, first_name: req.body.first_name, last_name: req.body.last_name }}, function (err, user) {
if (err) {
console.log(err);
res.render("editProfile", {user: req.body});
}
res.redirect("/users/me/");
});
},
but when I submit the form I am getting 404 error

Related

Cannot understand what create adapter is Sailsjs expecting

Whenever I try to execute the below code using POSTMAN, it shows me an error.
I even tried adding the create adapter by using "let create user = await User.create etc.." but it is still showing error.
Code
//Controller file content
module.exports = {
register: function(req, res){
data = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
description: req.body.description
};
console.log(data);
User.create(data)
.fetch()
.exec((err) => {
if(err){return res.serverError(err);}
});
}
I don't understand if the code is wrong or maybe I am missing something. Please help.
You could try:
register: function(req, res){
data = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
description: req.body.description
};
console.log(data);
User.create(data)
.exec((err, user) => {
if(err){return res.serverError(err);}
else {res.send(user)}
});
}
Or:
register: async function(req, res){
data = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
description: req.body.description
};
console.log(data);
const user = await User.create(data)
.intercept(err => new Error(err))
.fetch();
return res.send(user);
}

Registration form is not authenticate giving error 'MissingUsernameError'

I am trying to add registration detail to database. If i was adding only username and password by this then i am able to insert in mongo db but i am trying to insert name, email all thing then they are giving MissingUsernameError.
{
firstName: 'Name',
lastName: 'Last',
email: 'abc#gmail.com',
phone: '1111111111',
password: 'password'
}
{
MissingUsernameError: No username was given
at Promise.resolve.then (C:\Users\Music\web\node_modules\passport-local-mongoose\index.js:231:17)
at process._tickCallback (internal/process/next_tick.js:68:7) name:
'MissingUsernameError', message: 'No username was given' }
app.post("/register", function(req, res) {
console.log(req.body);
var newUser = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
phone: req.body.phone
});
User.register(newUser, req.body.password, function(err, user) {
if (err) {
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/");
});
});
});

MissingUsernameError: No username was given - Unsure where i'm going wrong

I'm using Node.js with Mongoose and Passport trying to get the user to save to the DB but keep encountering the error where No Username was given. I can get it to save if just using using username and password but as soon as I try to add more fields I get the issue. This is the code I have:
app.js
const userSchema = new mongoose.Schema ({
firstname: String,
lastname: String,
username: String,
password: String,
userLevel: {type: Number},
profileImage: String,
title: String
});
//ENABLE PASSPORT LOCAL
userSchema.plugin(passportLocalMongoose, {
selectFields: ' firstname lastname username password userLevel profileImage title'
});
//CREATE NEW model
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get('/control', (res, req) => {
if (req.isAuthenticated()) {
res.render('control');
} else {
res.redirect('/login')
}
});
app.post("/register", (req, res) => {
User.register(new User(
{firstname: req.body.firstname},
{lastname: req.body.lastname},
{username:req.body.username},
{userLevel: 1},
{profileImage:"not set"},
{title:"not set"}
),
req.body.password,
(err, user) => {
if (err) {
console.log(err);
console.log(req.body.username);
} else {
passport.authenticate('local')(req, res, () =>{
res.redirect('/control');
});
}
});
});
Figured it out! I was using individual objects rather that just the one object :
User.register((
{firstname: req.body.firstname,
lastname: req.body.lastname,
username: req.body.username,
userLevel: 1,
profileImage:"not set",
title:"not set"
}),
req.body.password,
(err, user) => {
if (err) {
console.log(err);
console.log(req.body.username);
} else {
passport.authenticate('local')(req, res, () =>{
res.redirect('/control');
});
}
});
});

update User information mongoose, MongoDB, NodeJS

I am working on an edit-profile page and i want to change/update the information of the documents in my mongooseDB, but my code does not update the document. Any suggestions?
router.get('/edit', isAuthenticated, function (req, res, next) {
res.render('profile/editprofile', {
user: req.user
});
});
router.post('/edit', isAuthenticated, function (req, res, next) {
User.update({_id: req.session.passport.user.id}, {
email: req.body.email,
password: req.body.password,
name: req.body.name,
phone: req.body.phone,
classc: req.body.classc,
//graduated: req.body.graduated;
major: req.body.major,
minor: req.body.mino,
linkedin: req.body.linkedin,
bio: req.body.bio
}, function (err){
if (err) console.log(err);
res.render('profile/profile', {
user: req.user
});
});
});
You have forgotten to add $set operator
router.post('/edit', isAuthenticated, function (req, res, next) {
console.log(req.user._id) //console like this
User.update({_id: req.user._id}, {$set: req.body}, function (err){
if (err) console.log(err);
res.render('profile/profile', {
user: req.user
});
});
});

Display Flash Error Messages to User After Mongoose Model Save

I have a page index.js which has a form to add users, and beside it a list of users in the database.
/routes/index.js
var express = require('express');
var router = express.Router();
var User = require('../schemas/user');
router.post('/create', function(req, res, next) {
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
user.save(function(err) {
if (err) {
console.log('user save error ' + err.errmsg);
return res.json(err.errmsg);
}
res.redirect('/');
});
});
/* GET home page. */
router.get('/', function(req, res, next) {
User.find(function (err, users) {
if (err) {
console.log('get error ' + err);
//return res.sendStatus(500);
}
res.render(
'index',
{
userList : users
}
);
});
});
module.exports = router;
/schemas/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
group: String,
created_at: Date,
updated_at: Date
});
var User = mongoose.model(
'User',
userSchema
);
module.exports = User;
Here is my view:
/views/index.pug
extends layout
block content
h1= title
p Welcome to #{title}
.container
.row
.col-sm
h1 Create User
form(
method='POST'
action='/create'
)
.form-group
label(for='username') Username:
input#username.form-control(
type='text',
placeholder='Enter username...',
name='username'
)
if usernameError
p.error= usernameError
.form-group
label(for='password') Password:
input#password.form-control(
type='password',
placeholder='Enter password...',
name='password'
)
if passwordError
p.error= passwordError
.form-group
label(for='email') Email:
input#email.form-control(
type='email',
placeholder='Enter email...',
name='email'
)
if emailError
p.error= emailError
button.btn.btn-primary(
type='submit',
) Submit
.col-sm
h2 User List
ul
each user in userList
li= user.username
As you can see, I have some conditionals in my index.pug file. What I want to do is if an error occurs I want to assign a message to a variable based on the error type (i.e. username already taken, or password too short) and pass that variable over to my pug view. The view will then render the message if the proper variable is set. Can somebody help me out? I'm mostly struggling with the fact that I also have to render the list of users, if I try to find users within the error catching part of the post node complains about headers already being set, i.e. If I have my router.post function like so:
router.post('/create', function(req, res, next) {
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
user.save(function(err) {
if (err) {
console.log('user save error ' + err.errmsg);
User.find(function (err2, users) {
if (err2) {
console.log('get error ' + err2);
//return res.sendStatus(500);
}
res.render(
'index',
{
userList : users,
usernameError: err.errmsg
}
);
});
}
res.redirect('/');
});
});
Then I expect to see the usernameError message filled in my view but instead I get an error from the node server:
user save error E11000 duplicate key error collection: test.users index: username_1 dup key: { : "John" }
POST /create 302 71.995 ms - 46
Error: Can't set headers after they are sent.
username: { type: String, required: true, unique: true },
it's because unique true.
Error: Can't set headers after they are sent.
Error because you haven't return error. Whenever error occure simply return like
if (err) return next(err)
provided that you are using express centralized error handler
check last lines of your app.js.All errors from next(err) goes here
app.use(function(err, req, res, next) {
console.error( err);
..............
});

Resources