data and salt arguments required node js - javascript

i am testing the authentication for my app and i got this error but could not solve it can you guys help me. Something is wrong with the bcrypt and salt etc but i could not figure out the reason.
I have add my package.json, Server and functions files. I had bcryptjs the old one in here first so i deleted and installed Bcrypt new one but still having a problem
Here is my package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.0",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.0",
"mongoose": "^6.8.3",
"nodemon": "^2.0.20"
}
}
Here is the server.js
const express = require('express')
const app = express()
require('dotenv').config();
app.use(express.json())
const dbConfig = require('./config/dbConfig');
const usersRoute = require("./routes/usersRoute");
app.use('/api/users', usersRoute);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}!`))
Here is my UserRoute
const router = require("express").Router();
const User = require("../models/userModel");
const bcrypt = require('bcrypt');
const jwt = require("jsonwebtoken");
// register user account
router.post("/register", async (req, res) => {
try {
// check if user already exists
let user = await User.findOne({ email: req.body.email });
if (user) {
return res.send({
success: false,
message: "User already exists",
});
}
// hash password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
req.body.password = hashedPassword;
const newUser = new User(req.body);
await newUser.save();
res.send({
message: "User created successfully",
data: null,
success: true,
});
} catch (error) {
res.send({
message: error.message,
success: false,
});
}
});
// login user account
router.post("/login", async (req, res) => {
try {
// check if user exists
let user = await User.findOne({ email: req.body.email });
if (!user) {
return res.send({
success: false,
message: "User does not exist",
});
}
// check if password is correct
const validPassword = await bcrypt.compare(
req.body.password,
user.password
);
if (!validPassword) {
return res.send({
success: false,
message: "Invalid password",
});
}
// check if user is verified
if (!user.isVerified) {
return res.send({
success: false,
message: "User is not verified yet or has been suspended",
});
}
// generate token
const token = jwt.sign({ userId: user._id }, process.env.jwt_secret, {
expiresIn: "1d",
});
res.send({
message: "User logged in successfully",
data: token,
success: true,
});
} catch (error) {
res.send({
message: error.message,
success: false,
});
}
});
module.exports = router;

Related

Why does a user need to log in multiple times to pass authentication?

this is my first time trying to write a simple authentication in express app.
express-session is used with MongoStore
I'm trying to learn what authentication is doing, so no Passport JS
User Flow
client sends request to access root path ('/)
access to root path triggers a middleware to check if this request is authenticated, by checking req.session.username
if this request is not authenticated, then res.redirect('/login')
'/login' will render a login page to user by res.render('login')
after filling log-in information, a POST to /login is sent from client
inside route('/login').post, if log-in information is correct, req.session.username is added manually, and then res.redirect('/')
res.redirect('/') should trigger the flow from the beginning
The problem I'm facing, is the last step res.redirect('/')
if using res.redirect('/'), sometimes log in once is enough, but most of the time I need to click log in multiple times to pass authentication
if using res.render() directly in route('/login').post() then it's always one click
What is happening behind?
Why sometimes res.redirect brings necessary information to root path, but sometimes not?
P.S. I'm testing this in http://localhost:3000
Package.json
"dependencies": {
"connect-mongo": "^4.6.0",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"express-handlebars": "^6.0.6",
"express-session": "^1.17.3",
"mongo-store": "^0.0.2"
}
app.js
require('dotenv').config()
const express = require('express')
const session = require('express-session')
const MongoStore = require('connect-mongo')
const { engine } = require('express-handlebars')
const app = express()
const PORT = process.env.PORT || 3000
const users = [
{
firstName: 'Tony',
email: 'tony#stark.com',
password: 'iamironman'
},
{
firstName: 'Steve',
email: 'captain#hotmail.com',
password: 'icandothisallday'
},
{
firstName: 'Peter',
email: 'peter#parker.com',
password: 'enajyram'
},
{
firstName: 'Natasha',
email: 'natasha#gamil.com',
password: '*parol##$!'
},
{
firstName: 'Nick',
email: 'nick#shield.com',
password: 'password'
}
]
const middleware = {
isUserValid(username, password) {
const user = users.find( user => user.email === username && user.password === password )
return user
},
isAuthenticated(req, res, next) {
if (req.session.username) return next()
else {
res.redirect('/login')
}
}
}
app.engine('handlebars', engine({ defaultLayout: 'main' }))
app.set('view engine', 'handlebars')
app.use(express.static('public'))
app.use(express.urlencoded({ extended: false }))
app.use(session({
secret: process.env.SECRET,
cookie: {
maxAge: 6000000,
secure: false,
httpOnly: true
},
store: MongoStore.create({
mongoUrl: process.env.MONGODB_URI
}),
resave: false,
saveUninitialized: false
}))
app.route('/').get(
middleware.isAuthenticated,
(req, res) => res.render('index', { name: req.session.username })
)
app.route('/login').get(
(req, res) => {
res.render('login')
}
)
app.route('/login').post((req, res) => {
const { email, password } = req.body
const user = middleware.isUserValid(email, password)
if (user) {
req.session.regenerate(err => {
if (err) next(err)
})
req.session.username = user.firstName
req.session.save(err => {
if(err) next(err)
res.render('index', { name: req.session.username }) // this always works for one-click
// res.redirect('/')
// this however, sometimes req.session.username is not brought to '/' path resulting in authentication failed
})
}
})
app.route('/logout').get(
(req, res) => {
req.session.username = null
req.session.save(err => {
if (err) {
return next(err)
}
req.session.regenerate((err) => {
if (err) {
return next(err)
}
res.redirect('/')
})
})
}
)
app.listen(PORT, () => console.log(`Express is listening on localhost:${PORT}`))

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.

passportjs req.isAuthenticated() returns False because passport.deserializeUser() never runs in certain browsers

Partially this error seem to be common in terms that req.Authenticated() is false but from what I have read it seems to affect all browsers according to the past post since they don't mention anything about being browser specific problem. So I have a heroku hosted web app, front end and back end are separate from each other.
Locally the problem does not exist regardless of browser but when moving to production then affects Chrome any chromium based browser but the ones that seem to not be affected are FireFox, PostMan (although nor a browser but is not affected),Electron APP (although I believe is chromium based but i don't know) ,when I go to the login route the back end simply skips over passport.deserializeUser() for affected browsers and thus req.isAuthenticated() returns false.
I have attempted all common solutions but none seem to fix the problem
Versions of dependancies
"axios": "^0.21.4",
"bcrypt": "^5.0.1",
"compression": "^1.7.4",
"connect-redis": "^5.2.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-session": "^1.17.2",
"knex": "^0.21.21",
"passport": "^0.5.0",
"passport-local": "^1.0.0",
"pg": "^8.7.1",
"redis": "^3.1.2",
Here is the code
server.js:
const passport = require("passport");
const LocalStrategy = require("passport-local");
const session = require("express-session");
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const compression = require("compression");
const isAuth =require("./location/login_Verification").isAuth;
const whitelist =
process.env.NODE_ENV === "development"
? ["http://localhost:3001"]
: [
"https://www.frontend.com",
"https://www.backend.com/",
];
const corsOption = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
credentials: true,
};
const app = express();
app.use(compression());
app.use(cookieParser());
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.use(
cors(corsOption)
);
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
store: new RedisStore({ client: redisClient }),
cookie: {
maxAge: 1000 * 60 * 60 * 24,
secure: false,//tried to add true does not work
},
})
);
require("./location/config/passport");
app.use(passport.initialize());
app.use(passport.session());
app.post(
"/login",
passport.authenticate("local", {
//session: true, tried this as well but nothing
successRedirect: "/login-success",
failureRedirect: "/login-fail",
})
);
/*It was suggested to use req.logIn to be more implicit but does not work
app.post("/login", function (req, res, next) {
passport.authenticate("local", function (err, user, info) {
if (info) {
console.log(info);
res.json({ success: "fail info" });
}
if (err) {
console.log(err);
return err;
}
if (!user) {
console.log(user);
res.json({ success: "fail user" });
}
req.logIn(user, function (err) {
if (err) {
return next(err);
}
req.session.save(function () {
console.log(req.session.passport);
res.redirect("/login-success");
});
});
})(req, res, next);
});*/
app.get("/login-success",/*delayhere*/ isAuth, (req, res) => {
const { hassignedup, reviewing_info } = req.user;
res.json({
success: true,
hassignedup: hassignedup,
reviewing_info: reviewing_info,
})
});
app.get("/login-fail", (req, res) => {
res.json({ success: false });
});
app.listen(process.env.PORT, () => {
});
passport.js:
const ValidPassword =
require("../location/passwordUtils").ValidPassword;
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
var knex= require("knex")(
process.env.NODE_ENV === "development"
? {
client: "pg",
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
},
}
: {
client: "pg",
connection: {
connectionString: process.env.DATABASE_URL_LOCAL,
ssl: {
rejectUnauthorized: true,
ca: fs.readFileSync("./config/file.pem").toString(),
},
},
}
);
const customFields = {
usernameField: "un",
passwordField: "pw",
};
const verifyCallback = (username, password, done) => {
knex
.select("*")
.from("users")
.where("username", username)
.then((user) => {
if (user[0] === undefined) {
return done(null, false);
} else {
return ValidPassword(password, user[0].pw).then((result) => {
if (result) {
let usercurrent = {
usercurrent: {
user_id: user[0].user_id,
hassignedup: user[0].hassignedup,
},
};
return done(null, usercurrent);
} else {
return done(null, false);
}
});
}
})
.catch((err) => {
done(err);
});
};
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
//console.log("deserial", user.usercurrent);
knex
.select("userid")
.from("users")
.where("userid", user.usercurrent.user_id)
.then((userobtained) => {
done(null, user.usercurrent);
})
.catch((err) => done(err));
});
passwordUtils.js
const bcrypt = require("bcrypt");
function genPassword(password) {
return bcrypt.hash(password, x).then((result) => {
return { hash: result };
});
}
function ValidPassword(password, hash) {
return bcrypt.compare(password, hash).then((result) => {
return result;
});
}
module.exports.ValidPassword = ValidPassword;
module.exports.genPassword = genPassword;
login_Verification.js
const isAuth = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
} else {
return res.status(401).json("not in");
}
};
module.exports = {
isAuth,
};
frontend.js ReactJS front end
....
onLogin=()=>{
axios({
method: "post",
url:
process.env.NODE_ENV === "development"
? "http://localhost:3000/login"
: "https://backend.com/login",
headers: {
"Access-Control-Allow-Origin":
process.env.NODE_ENV === "development"
? "http://localhost:3000"
: "https://frontend.com",
"Content-Type": "application/json",
},
data: {
un: this.state.username,
pw: this.state.pwd,
},
withCredentials: true,
}).then((result) => {
console.log("log in", result.data);
}
}
....
I have tried to do the common solutions Found throughout a good summary of the solutions out there here but I still have the problem. Some people suggested to add a delay just don't know where the delay goes or if where I placed it is a good place, any help would be appreciated
I have tried:
-create delay (dont know if correct place)
-make sure session and initialize are in correct order
-cors has credentials set to true
-withcredentials in the front end
-use a more implicit way to log in
-in session declaration set secure to true
seems to be the way the browser interacts with backend not sure where to go or what to try problem seems to be there since at least 2016
After realizing that since heroku servers SSL requests are req.connection.encrypted always undefined according to this PassportJS callback switch between http and https just add one line as follows
app.set('trust proxy', 1);

Why can I not create an User?

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 );

Why am I getting an Invalid shorthand property initializer error on my node JS app?

Hello SO comunity could you help me? I'm trying to connect through mongoose to a mongo db using using a object name user with its properties defined as a schema.
I have 3 files and this is my project structure
user.js (user model )
//mongoose is necesary
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
let usersSchema = new Schema({
name: {
type: String,
required: [true, 'name is required']
},
email:{
type: String,
required: [true, 'email is required']
},
password:{
type: String,
required: [true, 'password is required']
},
img:{
type: String,
},
role:{
type: String,
default: 'USER_ROLE'
},
state:{
type: Boolean,
default: true
},
social:{
type: Boolean,
default: false
}
});
//exports
module.exports = mongoose.model('User', usersSchema);
user.js (user controller)
/*
Endpoind for the user data*/
const express = require('express');
const User = require('../models/user_model')
const app = express()
/*************
** GET **
*************/
app.get('/usuarios', function (req, res) {
res.json('Hello World')
})
/*************
** POST ****
*************/
app.post('/usuarios', function (req, res) {
let body = req.body
let usuario = new User({
name = body.name,
email = body.email,
password = body.password,
role = body.role
})
usuario.save((err, userDB) => {
// if error
if (err) {
return res.status(400).json({
ok: false,
err
})
}
// if success
res.json({
ok: true,
user: userDB
})
})
})
/*************
** PUT **
*************/
app.put('/usuarios/:id', function (req, res) {
let id = req.params.id
res.json({
id
})
})
/*************
** DELETE **
*************/
app.delete('/usuarios', function (req, res) {
res.json('Hello World')
})
/*
Exports
*/
module.exports = app;
And the main file server.js
// dependencies
require ('./config/config'); // inmediactly loaded
const mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
const { json } = require('body-parser');
// declarations
const app = express()
// configuring body parser for express
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// temporal para pasar por referencia las rutas de usuarip
app.use(require('./controllers/user'))
// monguse settings conection
mongoose.connect('mongodb://localhost:27017/sales',{useNewUrlParser: true, useUnifiedTopology: true}, (err, resp)=>{
if (err) throw new err;
console.log('connected to mongodb')
}
);
app.listen(process.env.PORT, () => {
console.log('runing on port:',process.env.PORT );
})
and also package.json
{
"name": "node_repaso",
"version": "1.0.0",
"description": "a review poject",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"review"
],
"author": "Gerardo Guevara",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^5.9.28"
}
}
but I don't know why I get this error
Change
let usuario = new User({
name = body.name,
email = body.email,
password = body.password,
role = body.role
})
To
let usuario = new User({
name : body.name,
email : body.email,
password : body.password,
role : body.role
})
you are assigning value instead of passing json data to User Model
You cannot assign values to properties with = you need to use :
However here is a cleaner way to do it:
let { name, email, password, role } = req.body;
let usuario = new User({
name,
email,
password,
role
})

Categories