Why can I not create an User? - javascript

I´m trying to set up a register and login server with node.js and mongoose. So I have create an user model and an user route. Can someone find the mistake why I can´t create an user. I connect to Postman under POST : localhost:3000/users/register
my user model:
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
minlength: 1,
trim: true, //calls .trim() on the value to get rid of whitespace
unique: true, //note that the unique option is not a validator; we use mongoose-unique-validator to enforce it
},
password: {
type: String,
required: true,
minlength: 8,
},
});
//this enforces emails to be unique!
UserSchema.plugin(uniqueValidator);
//this function will be called before a document is saved
UserSchema.pre('save', function(next) {
let user = this;
if (!user.isModified('password')) {
return next();
}
//we generate the salt using 12 rounds and then use that salt with the received password string to generate our hash
bcrypt
.genSalt(12)
.then((salt) => {
return bcrypt.hash(user.password, salt);
})
.then((hash) => {
user.password = hash;
next();
})
.catch((err) => next(err));
});
module.exports = mongoose.model('User', UserSchema);
my routes user:
const express = require('express');
const bcrypt = require('bcryptjs');
const User = require('../models/user');
const router = express.Router();
//util function to check if a string is a valid email address
const isEmail = (email) => {
if (typeof email !== 'string') {
return false;
}
const emailRegex = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
return emailRegex.test(email);
};
router.post('/register', async (req, res) => {
try {
const { email, password } = req.body;
if (!isEmail(email)) {
throw new Error('Email must be a valid email address.');
}
if (typeof password !== 'string') {
throw new Error('Password must be a string.');
}
const user = new User({ email, password });
const persistedUser = await user.save();
res.status(201).json({
title: 'User Registration Successful',
detail: 'Successfully registered new user',
});
} catch (err) {
res.status(400).json({
errors: [
{
title: 'Registration Error',
detail: 'Something went wrong during registration process.',
errorMessage: err.message,
},
],
});
}
});
router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!isEmail(email)) {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Email must be a valid email address',
},
],
});
}
if (typeof password !== 'string') {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Password must be a string',
},
],
});
}
//queries database to find a user with the received email
const user = await User.findOne({ email });
if (!user) {
throw new Error();
}
//using bcrypt to compare passwords
const passwordValidated = await bcrypt.compare(password, user.password);
if (!passwordValidated) {
throw new Error();
}
res.json({
title: 'Login Successful',
detail: 'Successfully validated user credentials',
});
} catch (err) {
res.status(401).json({
errors: [
{
title: 'Invalid Credentials',
detail: 'Check email and password combination',
errorMessage: err.message,
},
],
});
}
});
module.exports = router;
my server :
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
const dotenv = require("dotenv");
const app = express();
dotenv.config();
//other imports
const usersRoute = require('./routes/users');
//other app.use statements
//connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true,
useUnifiedTopology: true},
() => console.log('Database connected')
);
mongoose.Promise = global.Promise;
const port = process.env.PORT || 3000;
//sets up the middleware for parsing the bodies and cookies off of the requests
app.use(bodyParser.json());
app.use(cookieParser());
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
module.exports = { app };
what I only get is this.:
Cannot POST /users/register

You didn't specify the path prefix in your server file. You should define:
app.use("/users", usersRoute );

Related

Express 404 error when trying to redirect to another route

I'm trying to test my Express server in Postman and am getting a 404 Not found error. It happens when I try to login to my demo user account through /users/demoLogin. From the console I see
POST /users/demoLogin 302 93.222 ms - 30
Executing (default): SELECT "id", "firstName", "lastName", "email", "hashedPassword", "createdAt", "updatedAt" FROM "Users" AS "User" WHERE "User"."id" = 1;
NotFoundError: Not Found
at /home/jas0123/noted/noted-api/app.js:48:8
at Layer.handle [as handle_request] (/home/jas0123/noted/noted-api/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/jas0123/noted/noted-api/node_modules/express/lib/router/index.js:328:13)
at /home/jas0123/noted/noted-api/node_modules/express/lib/router/index.js:286:9
at Function.process_params (/home/jas0123/noted/noted-api/node_modules/express/lib/router/index.js:346:12)
at next (/home/jas0123/noted/noted-api/node_modules/express/lib/router/index.js:280:10)
at /home/jas0123/noted/noted-api/node_modules/express/lib/router/index.js:646:15
at next (/home/jas0123/noted/noted-api/node_modules/express/lib/router/index.js:265:14)
at Function.handle (/home/jas0123/noted/noted-api/node_modules/express/lib/router/index.js:175:3)
at router (/home/jas0123/noted/noted-api/node_modules/express/lib/router/index.js:47:12)
GET /users/1 404 7.878 ms - 33
When I log the request object just before the 404 error I see:
url: '/users/1',
method: 'GET',
within the object, so it appears to be pointing to the route.
This is my app.js
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const { sequelize } = require('./db/models');
const session = require('express-session');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const usersRouter = require('./routes/users');
const { restoreUser } = require('./auth');
const { sessionSecret } = require('./config');
const app = express();
app.use(session({
name: 'noted.sid',
secret: sessionSecret,
resave: false,
saveUninitialized: false
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// set up session middleware
const store = new SequelizeStore({ db: sequelize });
app.use(
session({
secret: 'superSecret',
store,
saveUninitialized: false,
resave: false,
})
);
// restore user middleware
app.use(restoreUser);
// create Session table if it doesn't already exist
store.sync();
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log(req);
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
console.log(err)
res.json({error: err});
});
module.exports = app;
These are my user routes
const express = require('express');
const { check, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const {csurfProtection, asyncHandler} = require('./utils')
const db = require('../db/models');
const { loginUser, logoutUser } = require('../auth');
const router = express.Router();
if(process.env.NODE_ENV === 'production') router.use(csurfProtection)
// Validations middleware
const signupValidation = [
check("firstName")
.exists({ checkFalsy: true })
.withMessage('Please provide a value for First Name')
.isLength({ max: 50})
.withMessage('First Name must not be more than 50 characters long'),
check("lastName")
.exists({ checkFalsy: true })
.withMessage('Please provide a value for Last Name')
.isLength({ max: 50})
.withMessage('First Name must not be more than 50 characters long'),
check("email")
.exists({ checkFalsy: true })
.withMessage('Please provide a value for Email Address')
.isLength({ max: 150})
.withMessage('Email address must not be more than 255 characters long'),
check("password")
.exists({ checkFalsy: true })
.withMessage('Please provide a value for password')
.isLength({ max: 50})
.withMessage('Password must not be more than 50 characters long')
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})/)
.withMessage('Password should contain at least 1 lowercase letter, uppercase letter, number, and special character'),
check("confirmPassword")
.exists({ checkFalsy: true })
.withMessage('Please confirm password')
.custom((val, { req }) => val === req.body.password)
.withMessage('Password and password confirm do not match'),
]
const loginValidation = [
check("email")
.exists({ checkFalsy: true })
.withMessage('Please provide a value for Email Address'),
check("password")
.exists({ checkFalsy: true })
.withMessage('Please provide a value for password')
]
/* GET user */
router.get('/:id(\d+)', asyncHandler(async function(req, res, next) {
console.log("Hit this route!")
const learningStacks = await db.LearningStack.findAll({ where: { userID: req.params.id, } });
return res.json({user: res.locals.user.dataValues, learningStacks})
}));
router.get("/signup", csurfProtection, function(req, res, next) {
const csrfToken = req.csrfToken()
res.json({csrfToken, user: {}});
})
router.post("/signup", signupValidation, asyncHandler(async function(req, res) {
const errors = validationResult(req).errors.map(e => e.msg);
// create user object with fields to re-render if there are errors
const prefillUser = db.User.build({
email: req.body.email,
firstName: req.body.firstName,
});
if (errors.length > 0) {
return res.json({ user: prefillUser, errors, csrfToken: req.csrfToken()});
} else {
// check if the e-mail is available
emailPresent = await db.User.count( { where: { email: req.body.email } })
if (emailPresent) {
errors.push("A user with this e-mail already exists.")
return res.json({ user: prefillUser, errors, csrfToken: req.csrfToken()});
}
const saltRounds = 10;
const salt = await bcrypt.genSalt(saltRounds);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
const user = await db.User.create({
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
hashedPassword,
});
loginUser(req, res, user);
return res.redirect(req.session.redirectTo || "/")
}
}));
router.post('/login', loginValidation, asyncHandler (async (req, res, next) =>{
const errors = validationResult(req).errors.map(e => e.msg);
if (errors.length > 0) {
return res.json( {errors, csrfToken: req.csrfToken()});}
else {
const user = await db.User.findOne({ where: { email: req.body.email } });
if (user) {
const isPasswords = await bcrypt.compare(
req.body.password,
user.hashedPassword.toString(),
);
if (isPasswords) {
loginUser(req, res, user);
return res.redirect(req.session.redirectTo ||`/users/1`);
}
}
}
errors.push("Email address or password incorrect.");
return res.json({ errors, csrfToken: req.csrfToken() });
}))
router.get('/login', csurfProtection, (req, res, next) =>{
return res.json({csrfToken: req.csrfToken()});
})
router.post('/logout', asyncHandler(async (req, res, next) => {
logoutUser(req);
return res.redirect(req.session.redirectTo || "/");
}))
router.post('/demoLogin', csurfProtection, loginValidation, asyncHandler (async (req, res, next) =>{
errors=[]
const user = await db.User.findOne({ where: { email: 'demo_noted_user#gmail.com' } });
if (user) {
const isPasswords = await bcrypt.compare(
'Password1!',
user.hashedPassword.toString(),
);
if (isPasswords) {
loginUser(req, res, user);
return res.redirect(req.session.redirectTo || "/users/1");
}
}
errors.push("Demo login not found.");
return res.json({ errors, csrfToken: req.csrfToken() });
}))
module.exports = router;
I'm not seeing the console.log("Hit this route!") in my console. Am I not redirecting properly?
const db = require('./db/models');
const loginUser = (req, res, user) => {
req.session.auth = { userId: user.id }
}
const restoreUser = async (req, res, next) => {
if (req.session.auth) {
try {
const { userId } = req.session.auth;
const user = await db.User.findByPk(userId);
if (user) {
console.log(user, "user <-- THIS LOGS");
res.locals.authenticated = true;
res.locals.user = user;
next();
return
}
} catch (e) {
console.log(e, "THIS IS E")
res.locals.authenticated = false;
next(e);
return
}
}
res.locals.authenticated = false;
next();
}
const logoutUser = (req, res) => {
delete req.session.auth;
}
module.exports = {
loginUser,
restoreUser,
logoutUser
}
These are my auth middlewares
It seems that you're hitting the /users/1 (/users/:id) endpoint, however, you have the route defined as router.get('/:id(\d+)' which is missing the /users/ prefix.
Try using this:
router.get('/users/:id(\d+)'

How to fix JsonWebTokenError in node.js using express and reactjs?

I am trying to show the page only if the Jsonwebtoken is verified and the user is logged on to the website, else show him the sign-in page.
However, I can see the token is generated in MongoDB, and also when I console log I can see that it is all good. But the issue is when I try to verify it using an already generated jwt token i.e.
req.cookies.signinToken
it shows an error.
Please the detail code below:
On app.js
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const express = require("express");
const app = express();
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
dotenv.config({ path: "./config.env" });
require("./db/connection");
app.use(express.json());
app.use(cookieParser());
app.use(require("./router/route"));
const PORT = process.env.PORT;
app.listen(5000, () => {
console.log(`server running on ${PORT}`);
});
On route.js
const express = require("express");
const bcrypt = require("bcrypt");
const router = express.Router();
const jwt = require("jsonwebtoken");
require("../db/connection");
const User = require("../model/newUserSchema");
const auth = require("../middleware/auth");
// router.get("/", (req, res) => {
// res.send("hello am backend sever");
// });
//Signup or Register Part
router.post("/signup", async (req, res) => {
const { username, email, cpassword, retypePassword } = req.body;
if (!username || !email || !cpassword || !retypePassword) {
return res.status(422).json({ error: "please enter valid details" });
}
try {
const UserExist = await User.findOne({ email: email });
if (UserExist) {
return res.status(422).json({ error: "email already exist" });
} else if (cpassword !== retypePassword) {
return res.status(422).json({ error: "password incorrect" });
} else {
const user = new User({
username,
email,
cpassword,
retypePassword,
});
const userResgister = await user.save();
if (userResgister) {
return res.status(201).json({ message: "signup successfully" });
}
}
} catch (error) {
console.log(error);
}
});
//Login Part
router.post("/signin", async (req, res) => {
try {
const { email, cpassword } = req.body;
if (!email || !cpassword) {
return res.status(400).json({ error: " please enter valid credentials" });
}
const userLogin = await User.findOne({ email: email });
const token = userLogin.generateAuthToken();
res.cookie("signinToken", token, {
expires: new Date(Date.now() + 25892000000),
httpOnly: true,
});
if (userLogin) {
const isMatch = await bcrypt.compare(cpassword, userLogin.cpassword);
if (isMatch) {
return res.status(200).json({ message: "sigin in scuccessfully" });
} else {
return res.status(400).json({ error: " Invalid credentials" });
}
} else {
return res.status(400).json({ error: " Invalid credentials " });
}
} catch (error) {
console.log(error);
}
});
//watchlistpage
router.get("/watchlist", auth, (req, res) => {
console.log(" this is jwt token test " + req.cookies.signinToken);
res.send(req.rootuser);
console.log(req.rootuser);
});
module.exports = router;
On newUserSchema.js:
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const newUserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
cpassword: {
type: String,
required: true,
},
retypePassword: {
type: String,
required: true,
},
tokens: [
{
token: {
type: String,
required: true,
},
},
],
});
newUserSchema.pre("save", async function (next) {
if (this.isModified("cpassword")) {
this.cpassword = await bcrypt.hash(this.cpassword, 12);
this.retypePassword = await bcrypt.hash(this.retypePassword, 12);
}
next();
});
newUserSchema.methods.generateAuthToken = async function () {
try {
let token = jwt.sign({ _id: this._id }, process.env.SECRETKEY);
this.tokens = this.tokens.concat({ token: token });
await this.save();
return token;
} catch (error) {
console.log(error);
}
};
const User = mongoose.model("newUser", newUserSchema);
module.exports = User;
On auth.js (this is also my middleware)
const jwt = require("jsonwebtoken");
const User = require("../model/newUserSchema");
const Auth = async (req, res, next) => {
try {
console.log(JSON.stringify(req.cookies.signinToken) + " this is jwt token test");
const token = req.cookies.signinToken;
const verifytoken = jwt.verify(token, process.env.SECRETKEY);
const rootuser = await User.findOne({ _id: verifytoken._id, "tokens.token": token });
if (!rootuser) {
throw new Error("user not found");
}
req.token = token;
req.rootuser = rootuser;
req.UserID = rootuser._id;
next();
} catch (error) {
res.status(401).send("Unauthorized access");
console.log(error);
}
};
module.exports = Auth;
The API call result in postman
The terminal error :
when I try to console log on route.js inside Signin page i see promise pending
const token = userLogin.generateAuthToken();
console.log(token);
res.cookie("signinToken", token, {
expires: new Date(Date.now() + 25892000000),
httpOnly: true,
});
Could you please help to correct the error also please let me know why is this error coming?
Thanks a million in advance for any tips or suggestions.
Hi Thanks for the help
I just saw that my token was returning a promise, I did not add the keyword await before the token other thing was I was trying to access it before the validation, hence it was showing me nodata and error.
Please see the correct code below:
//Login Part
router.post("/signin", async (req, res) => {
try {
const { email, cpassword } = req.body;
if (!email || !cpassword) {
return res.status(400).json({ error: " please enter valid credentials" });
}
const userLogin = await User.findOne({ email: email });
if (userLogin) {
const isMatch = await bcrypt.compare(cpassword, userLogin.cpassword);
const token = await userLogin.generateAuthToken();
console.log(token);
res.cookie("signinToken", token, {
expires: new Date(Date.now() + 25892000000),
httpOnly: true,
});
if (isMatch) {
return res.status(200).json({ message: "sigin in scuccessfully" });
} else {
return res.status(400).json({ error: " Invalid credentials" });
}
} else {
return res.status(400).json({ error: " Invalid credentials " });
}
} catch (error) {
console.log(error);
}
});
I hope this might help other learners too.
Thanks.

Getting error while logging in due to unknown bcrypt issue

I'm working on the backend with nodejs and mongodb . After coding authentication part i'm having unknown issue and i think it's from bcrypt :(
please have a look at my code.
USER MODEL CODE -
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const validator = require("validator");
require("dotenv").config();
const userSchema = mongoose.Schema(
{
email: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail) {
throw new Error("Invalid Email");
}
},
},
password: {
type: String,
required: true,
trim: true,
},
role: {
type: String,
enum: ["user", "admin"],
default: "user",
},
name: {
type: String,
required: true,
maxlength: 21,
},
phone: {
required: true,
type: Number,
maxlength: 12,
},
},
{
timestamps: true,
},
);
userSchema.pre("save", async function (next) {
if (this.isModified("password")) {
// hash the password
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(this.password, salt);
this.password = hash;
}
next();
});
userSchema.methods.generateToken = function () {
const userObj = { id: this._id.toHexString(), email: this.email };
const token = jwt.sign(userObj, process.env.DB_SECRET, {
expiresIn: "3d",
});
return token;
};
userSchema.statics.emailTaken = async function (email) {
const user = await this.findOne({ email });
return !!user;
};
const User = mongoose.model("User", userSchema);
module.exports = {
User,
};
USER API CODE (Please avoid those bunch of console log statements as i had added them for debugging purpose) -
const express = require("express");
const router = express.Router();
require("dotenv").config();
const { User } = require("../../models/userModel");
const bcrypt = require("bcrypt");
// const comparePassword = async (userPassword) => {
// console.log("Comparing password with bcrypt");
// const match = await bcrypt.compare(userPassword, this.password);
// console.log(match);
// return match;
// };
router.route("/signup").post(async (req, res) => {
const { email, password, name, phone } = req.body;
console.log(req.body);
try {
// Check if user email exists
if (await User.emailTaken(email)) {
return res.status(400).json({ message: "Email already exists" });
}
// create user instance and hash password
const user = new User({
email: email,
password: password,
name: name,
phone: phone,
});
// generate jwt token
console.log("user is saving");
const token = user.generateToken();
const userDoc = await user.save();
// send email
// save....send token with cookie
res.cookie("access-token", token).status(200).send(returnUserDoc(userDoc));
} catch (error) {
res
.status(400)
.json({ message: "Error while creating user", error: error });
}
});
router.route("/login").post(async (req, res) => {
try {
// Find user
console.log("Finding User........");
let user = await User.find({ email: req.body.email });
if (!user) {
return res.status(400).json({ message: "Invalid Credentials" });
}
// Compare Password
console.log("Comparing password with bcrypt");
const match = await bcrypt.compare(req.body.password, user.password);
console.log("password compared");
console.log(match);
if (match == false) {
return res.status(400).json({ message: "Invalid Credentials" });
}
console.log("Password Matched");
// Generate Token
console.log("Generating Token........");
const token = user.generateToken();
// Response
console.log("Sending Response........");
res.cookie("access-token", token).status(200).send(returnUserDoc(user));
} catch (error) {
console.log("Error");
res.status(400).json({ message: "Error while loggin in", error: error });
}
});
// functions
const returnUserDoc = (userDoc) => {
return {
_id: userDoc._id,
name: userDoc.name,
email: userDoc.email,
phone: userDoc.phone,
};
};
module.exports = router;
CONSOLE LOGS -
listening on port 3001
Database Connected
Finding User........
Comparing password with bcrypt
Error
I have found that code is executing successfully just before const match = await bcrypt.compare(req.body.password, user.password); this line
On console.log(error.message); i'm getting this -
Error: data and hash arguments required
at Object.compare (D:\CovidHelpers\CovidHelpers\node_modules\bcrypt\bcrypt.js:208:17)
at D:\CovidHelpers\CovidHelpers\node_modules\bcrypt\promises.js:29:12
at new Promise (<anonymous>)
at Object.module.exports.promise (D:\CovidHelpers\CovidHelpers\node_modules\bcrypt\promises.js:20:12)
at Object.compare (D:\CovidHelpers\CovidHelpers\node_modules\bcrypt\bcrypt.js:204:25)
at D:\CovidHelpers\CovidHelpers\server\routes\api\users.js:60:32
at processTicksAndRejections (internal/process/task_queues.js:93:5)
data and hash arguments required
Please help me fix this :)
Thank You

can not retrieve values from req.session

i'm new to nodejs, i'm using express-session for my project
I can't retrieve session values nowhere than my login route
I see many people have the same problems
Any recommend or help would be awesome ! you all have a nice day !
Here's my login route
route.post('/verify', (req, res) => {
const email = req.body.email;
const pass = req.body.password;
userModel.findOne({ email: email }, (err, data) => {
if (err) {
console.log(err);
res.status(500).json({
success: false,
message: error.message
});
}
else {
if (data !== null) {
if (!bcryptjs.compareSync(pass, data.password)
) {
res.status(400).json({
success: false,
message: "Wrong Password"
})
}
else {
req.session.currentUser = {
email: data.email,
};
console.log(req.session);
res.status(200).json({
success: true,
message: "Login Success",
data: {
email: data.email,
name: data.name,
id:data.id,
}
})
}
}
else {
res.status(404).json({
success: false,
message: "Email doesn't exist"
})
}
}
})
})
Here's my server.js setup:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const session = require('express-session');
const bcryptjs = require('bcryptjs');
const passport = require('passport');
var Schema = mongoose.Schema;
require('./passport/facebook-auth')(passport);
require('dotenv').config();
const passportSetup = require('./passport/google-auth');
const authRoutes = require('./routes/auth-routes');
const userRoutes = require('./user/user.routes')
const userModel = require('./user/user.schema');
// connect to mongodb
mongoose.connect('mongodb://' + process.env.USER + ':' + process.env.PASS + '#localhost:27017/' + process.env.DATABASE + '?authSource=admin', { useNewUrlParser: true, useUnifiedTopology: true }, (e) => {
//FIXME: tim cach viet khac
if (e)
throw e;
else {
console.log("MongoDB Connected...");
// basic init
const server = express();
server.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: false,
}));
server.use(express.static('public'));
// set up cors to allow us to accept requests from our client
server.use(cors({
origin: "http://localhost:3000", // allow to server to accept request from different origin
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true // allow session cookie from browser to pass through
})
);
server.use(bodyParser.json());
// set up session cookies
// initialize passport
server.use(passport.initialize());
server.use(passport.session());
// set up route
server.use('/auth', authRoutes);
server.use('/users', userRoutes);
server.listen(process.env.PORT || 5000, (err) => {
if (err)
throw err;
else
console.log("Server listening on port 5000...");
console.log('hadm x tanhng...');
console.log('ununneee here we come');
});
}
})
after logging in , the session is destroyed automatically
thank you once again

Getting NodeJS delete route non functioning

I did the registration portion successfully now I am trying to delete the registered user by id . This is how I did
user controller
const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
And in my index router
const express = require ('express');
const router = express.Router();
const ctrlUser = require ('../controllers/user.controller.js');
// routing functions
router.post('/register' , ctrlUser.register);
router.delete('/:userId' , (req, res, next) =>{
User.remove({_id: req.params.userId})
.exec()
.then(result => {
res.status(200).send(["Deleted"]);
})
.catch(err =>{
if (err.code == 500)
res.status(500).send(["Didn't get deleted"]);
else
return next(err);
});
});
module.exports = router;
When I am testing in postman I am not getting any response. Where did I make the mistake ? Something am I missing out ?
EDIT:- Including user.model
const mongoose = require ('mongoose');
const bcrypt = require('bcryptjs');
//define user schema
var userSchema = new mongoose.Schema({
fullName : {
type: String,
required: "Full name can't be empty"
},
email : {
type: String,
required: "Email can't be empty",
unique: true
},
password : {
type: String,
required: "Password can't be empty",
minlength: [6 ,"Password must be atleast 6 character long"]
},
phoneNumber : {
type: String,
required: "Reqired for further contact.Can't be empty"
},
saltSecret: String //this is user for encryption and decryption of password
});
mongoose.model('User', userSchema);

Categories