the node server is braked after getting an error - javascript

I'm new in NodeJS I got this error ( this.$__.validationError = new ValidationError(this);)
I try to use try{..}catch(e){..} but it still the same problem inside post user but always the same
I'm confused what I should do
the error
C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:3125
this.$__.validationError = new ValidationError(this);
^
ValidationError: User validation failed: password: Path `password` is required.
at model.Document.invalidate (C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:3125:32)
at C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:2913:17
at C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\schematype.js:1349:9
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
errors: {
password: ValidatorError: Path `password` is required.
at validate (C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\schematype.js:1346:13) at SchemaString.SchemaType.doValidate (C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:2905:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: {
validator: [Function (anonymous)],
message: 'Path `password` is required.',
type: 'required',
path: 'password',
value: undefined
},
kind: 'required',
path: 'password',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
user schema
const mongoose = require('mongoose')
const joi = require('joi')
const User = mongoose.model('User', new mongoose.Schema({
fullname:{
type:String,
required:true,
minlength:3,
maxlength:44
},
email:{
type:String,
required:true,
unique:true,
minlength:3,
maxlength:255
},
password:{
type:String,
required:true,
minlength:3,
maxlength:1025
}
}))
const validateUser = (body , res)=>{
const schema = joi.object({
fullname:joi.string().min(3).max(44).required(),
email:joi.string().min(3).max(255).required().email(),
password:joi.string().min(8).max(255).required()
})
const {error} = schema.validate(body)
if(error){
return res.status(404).send(error.message)
}
}
module.exports = {User,validateUser}
user routes
const express = require('express')
const router = express.Router()
const {User , validateUser} = require('../model/user')
//add new user
router.post('/' , async(req,res)=>{
validateUser(req.body , res)
//add the new user
const user = new User({
fullname:req.body.fullname,
email:req.body.email,
password:req.body.password
})
await user.save()
res.send(user)
})
module.exports = router
index.js
const mongoose = require('mongoose')
const app = express()
//for devlopment envirement
if(app.get('env') === 'development'){
app.use(morgan('tiny'))
}
mongoose.set('strictQuery', false);
mongoose.connect("mongodb://localhost:27017/expDB", { useNewUrlParser: true })
.then(()=> console.log("connected to database"))
.catch((error)=>console.error("there is an error" + error))
//using the middlewares
app.use(helmet())
app.use(express.json())
app.use('/employees', employees)
app.use('/user' , user)
//running the server
const PORT = process.env.PORT || 3000
app.listen(PORT , ()=>{
console.log(`app ronning on PORT ${PORT}...`)
})
when I added try catch in post user I got this error
node:internal/errors:477
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:387:5)
at ServerResponse.setHeader (node:_http_outgoing:603:11)
at ServerResponse.header (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:174:12)
at ServerResponse.json (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:278:15)
at ServerResponse.send (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:162:21)
at C:\Users\toshiba\Desktop\express project\routes\user.js:18:19
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
post req
//add new user
router.post('/' , async(req,res)=>{
try{
validateUser(req.body , res)
//add the new user
const user = new User({
fullname:req.body.fullname,
email:req.body.email,
password:req.body.password
})
await user.save()
res.send(user)
}catch(err){
res.status(404).send(err)
}
})

Related

When loging in I get Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Sorry this is my first attempt at doing backend, it's probably a silly question. I have an index.js like so:
const express = require('express')
const app = express();
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const userRoute = require('./routes/user')
const authRoute = require('./routes/auth')
const PORT = process.env.PORT || 5000
dotenv.config()
mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log('db connection succesful'))
.catch((err) => {
console.log(err)
})
app.use(express.json())
app.use('/api/auth', authRoute)
app.use('/api/users', userRoute)
app.listen(PORT, () =>{
console.log(`backend server is running! on ${PORT}`)
})
My auth.js looks like:
const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
//REGISTER
router.post("/register", async (req, res) => {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try {
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json(err);
}
});
//LOGIN
router.post('/login', async (req, res) => {
try{
const user = await User.findOne({ username: req.body.username });
!user && res.status(401).json("Wrong User Name");
password = user.password
password !== req.body.password && res.status(401).json("Wrong credentials!");
res.status(200).json(user)
} catch(err) {
res.status(500).json(err);
}
});
module.exports = router;
And not sure if this is relevant but my User.js like so:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isAdmin: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
I am sending a JSON object to my register route:
{
"username": "test",
"email": "100#gmail.com",
"password": 123456
}
Which works. I get the following response in the body when posting to http://localhost:5000/api/auth/register:
{
"username": "test",
"email": "100#gmail.com",
"password": "123456",
"isAdmin": false,
"_id": "62fd49a6baa5717b67a885df",
"createdAt": "2022-08-17T20:03:50.776Z",
"updatedAt": "2022-08-17T20:03:50.776Z",
"__v": 0
}
But then when I try post an object to my login (http://localhost:5000/api/auth/login):
{
"username": "test",
"password": "123456"
}
I get the following error:
~/code/IaaS/app$ npm start
> app#0.1.0 start
> nodemon index.js
[nodemon] 2.0.19
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
backend server is running! on 5000
db connection succesful
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:278:15)
at /home/a7dc/code/IaaS/app/routes/auth.js:37:25
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
What am I doing wrong?
Thank you to Ariel for their answer. I have updated the code to the following:
//LOGIN
router.post('/login', async (req, res) => {
try{
const user = await User.findOne({ username: req.body.username });
!user && res.status(401).json("Wrong User Name");
password = user.password
password !== req.body.password && res.status(401).json("Wrong credentials!");
if (password !== req.body.password) {
return res.status(401).json("Wrong credentials!");
} else {
return res.status(200).json(user)
}
} catch(err) {
console.log('error')
return res.status(500).json(err);
}
});
module.exports = router;
Which gives the error:
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
backend server is running! on 5000
db connection succesful
error
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/home/a7dc/code/IaaS/app/node_modules/express/lib/response.js:278:15)
at /home/a7dc/code/IaaS/app/routes/auth.js:42:32
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
The problem is that you are sending a response twice (the program is not stopping when you send a response). Here you are sending a response with status 401 and then a response with status 200.
password !== req.body.password && res.status(401).json("Wrong credentials!");
res.status(200).json(user)
Probably, you want to send 401 if the password is different and 200 otherwise
if (password !== req.body.password) {
res.status(401).json("Wrong credentials!");
} else {
res.status(200).json(user)
}
Or maybe, just "return" when the response is sent. Example:
return res.status(XXX).json({ something: "something})
"Cannot set headers after they are sent to the client" means that one response is already sent so you can't set the headers again.

Facing this error while implementing this forgot password route or sending post request through postman

Here are the screenshots and code attached
Code:
exports.forgotPassword = async function(req, res, next) {
//Check if user exists
const user = await User.findOne({ email: req.body.email })
if (!user) {
return next(new AppError('There is no user with this email address', 404))
}
//Generate the random reset token
const resetToken = user.createPasswordResetToken()
await user.save({ validateBeforeSave: false });
//send it to user's mail
const resetURL = `${req.protocol}://${req.get('host')}/api/users/resetPassword/${resetToken}`;
const message = `Forgot your Password? Submit a patch request with your password and confirm password to ${resetURL}`
try {
await sendEmail({
email: user.email,
subject: 'Your password reset token(valid for 10 min)'
})
res.status(200).json({
status: 'success',
message: 'Token sent to Email'
})
} catch (err) {
user.passwordResetToken = undefined;
user.passwordResetExpires = undefined;
await user.save({ validateBeforeSave: false });
return next(new AppError('There was an error sending the email. Please try again later!'), 500);
}
}
Error Message :
Error: There was an error sending the email. Please try again later!
at exports.forgotPassword (D:\FYP\controllers\authController.js:94:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Error: getaddrinfo ENOTFOUND smtp.mailtrap.io;
at GetAddrInfoReqWrap.onlookup [as oncomplete]
(node:dns:71:26) {
errno: -3008,
code: 'EDNS',
syscall: 'getaddrinfo',
hostname: 'smtp.mailtrap.io;',
command: 'CONN'
}
look at my code
it used express.js with typescript
use ndoemailer to send email
https://nodemailer.com/about/
public async forgot(entity: AuthEntity): Promise<void> {
if (isEmpty(entity)) throw new HttpException(StatusCodes.BAD_REQUEST, i18n.t("api.commons.reject"));
let findUser: IUser;
if (entity.email !== undefined) {
findUser = await this.userModel.findOne({ email: entity.email });
if (!findUser) {
// #ts-ignore
await ipActivityModel.storeIp(false, "forgot", entity);
throw new HttpException(StatusCodes.CONFLICT, i18n.t("auth.youAreNotEmail"));
}
await this.sendForgotEmail(findUser.email, entity.resetToken);
}
}
public async sendForgotEmail(email: string, hash: string): Promise<void> {
const transporter = nodemailer.createTransport({
host: config.get("email.host"),
port: config.get("email.port"),
secure: config.get("email.secure"), // true for 465, false for other ports
auth: config.get("email.auth")
});
const mailContext = {
siteAddress: config.get("siteAddress"),
emailForgotTitle: i18n.t("auth.emailForgotTitle"),
emailForgotGuide: i18n.t("auth.emailForgotGuide"),
emailActivateHash: i18n.t("auth.emailActivateHash"),
hash: hash,
emailForgotVisit: i18n.t("auth.emailForgotVisit"),
emailActivateIgnore: i18n.t("auth.emailActivateIgnore"),
emailForgotResetFrom: i18n.t("auth.emailForgotResetFrom")
};
const template = await ejs.renderFile("./dist/modules/auth/views/forgot.html", mailContext);
const mailOptions = {
from: config.get("email.fromEmail"),
to: email,
subject: config.get("siteAddress") + " (" + i18n.t("api.events.emailForgot") + ")",
html: template
};
let isSend = await transporter.sendMail(mailOptions);
if (!isSend.messageId) {
throw new HttpException(StatusCodes.CONFLICT, i18n.t("auth.emailSendErrorForgot"));
}
}

Node.js throws TypeError: Cannot destructure property 'firstName' of 'req.body' as it is undefined, even though it works for an other post request

So I know there are tons of similar questions out there, and I've read most of them in the past few days. However I didn't find any solution to my problem. The app is about users can post memories(cards) etc... Point is, when I create a new card with POST request, there is no problem, but when I want to sign up a user then all hell breaks loose and throws this error:
(node:2732) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property 'firstName' of 'req.body' as it is undefined.
at signup (file:///E:/projects/personal/memories-app/backend/controllers/user.controller.js:39:13)
at Layer.handle [as handle_request] (E:\projects\personal\memories-app\backend\node_modules\express\lib\router\layer.js:95:5)
at next (E:\projects\personal\memories-app\backend\node_modules\express\lib\router\route.js:137:13)
I don't know that could be the problem, because other functions work so dunno really.
Here are the codes
server.js
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import postRoutes from './routes/posts.routes.js';
import userRoutes from './routes/users.routes.js';
const app = express();
dotenv.config();
app.use(express.json({ extended: true }));
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use('/posts', postRoutes);
app.use('/users', userRoutes);
app.get('/', (req, res) => {
res.send('Hello to Memories API');
});
const PORT = process.env.PORT || 5000;
mongoose
.connect(process.env.CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() =>
app.listen(PORT, () => console.log(`Server running on port: ${PORT}`))
)
.catch((error) => console.log(error.message));
mongoose.set('useFindAndModify', false);
user.model.js
import mongoose from 'mongoose';
const userSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
id: { type: String },
});
export default mongoose.model('User', userSchema);
the sign up method from user.controller.js
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import User from '../models/user.js';
export const signup = async (res, req) => {
const { firstName, lastName, email, password, confirmPassword } = req.body;
try {
const existingUser = await User.findOne({ email });
if (existingUser)
return res.status(400).json({ message: 'User already exists' });
if (password !== confirmPassword)
return res.status(400).json({ message: "Passwords don't match" });
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({
email,
password: hashedPassword,
name: `${firstName} ${lastName}`,
});
const token = jwt.sign(
{ email: result.email, id: result._id },
'test',
{
expiresIn: '1h',
}
);
res.status(200).json({ result, token });
} catch (error) {
res.status(500).json({ message: 'Something went wrong.' });
}
};
and just to see the createPost method (which works) from post.controller.js
import PostMessage from '../models/postMessage.js';
import mongoose from 'mongoose';
export const createPost = async (req, res) => {
const post = req.body;
console.log(post);
const newPost = new PostMessage(post);
try {
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
res.status(409).json({ message: error.message });
}
};
And there is no problem with the front-end because when I simply console.log the req, I can see the body, but if I were to clg the req.body, then it is undefined. I've tried it with postman also, but no luck.
I would appreciate any insight on this! Thanks in advance!
You need to swap the order of res and req in the signup function, replace:
export const signup = async (res, req) => {
by:
export const signup = async (req, res) => {
Your User model does not have a firstName, lastName, and confirmPassword types use { name, email, password, } = req.body to sign up a new user.
In your project frontend use
name email, password, confirmPassword to register a use and email, password to log users in.

Table 'todoblog.users' doesn't exist

I'm trying to create a small todo blog using sequelize. But I get stacked in this error. The table is not created. I created the database using SQL, then I used sequelize in the model and controller.
schema.sql
(here I created a database and run it manually in the terminal)
DROP DATABASE IF EXISTS toDoBlog;
CREATE DATABASE toDoBlog;
USE toDoBlog;
connection.js
(Here when I'm connecting to the database)
// connection
const sequelize = new Sequelize("toDoBlog", "name", "password", {
host: "localhost",
dialect: "mysql",
host: "localhost",
});
// testing connection to database
sequelize
.authenticate()
.then(() => {
console.log("Connection has been established successfully.");
})
.catch((err) => {
console.error("Unable to connect to the database:", err);
});
module.exports = sequelize;
userModel.js
(creating the table and define it)
const Sequelize = require("sequelize");
const connection = require("../connexion/connexion.js");
const User = connection.define("user", {
user_id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: { type: Sequelize.STRING, allowNull: false },
email: { type: Sequelize.STRING, allowNull: false },
password: { type: Sequelize.STRING, allowNull: false },
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
});
module.exports = User;
userController.js
(create/find/delete operations)
const UserModel = require("../database/Model/userModel.js");
module.exports.createOne = async (req, res) => {
const info = req.body;
console.log(info);
const user = await UserModel.create({
name: info.name,
email: info.email,
password: "hash(info.password)",
});
};
userRouter.js
(router for the controllers)
const userController = require("../controllers/userController.js");
var express = require("express");
var router = express.Router();
router.post("/createOne", userController.createOne);
module.exports = router;
index.js
(main file)
const express = require("express");
const bodyParser = require("body-parser");
const connextion = require("./database/connexion/connexion.js");
const userRouter = require("./routers/userRouter.js");
// const blogRouter = require("./routers/blogRouter.js");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("express working");
});
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// to link the front. I need to get more info about it.
app.use(express.static(__dirname + "/../react-client/dist"));
app.use("/api/user", userRouter);
// app.use("/api/blogs", blogRouter);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
this is the error
[nodemon] starting `node server/index.js`
Example app listening at http://localhost:3000
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
{ name: 'SEMER', email: 'semer', password: 'smeer' }
Executing (default): INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);
C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\mysql\query.js:256
return new sequelizeErrors.DatabaseError(err);
^
DatabaseError [SequelizeDatabaseError]: Table 'todoblog.users' doesn't exist
at Query.formatError (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\mysql\query.js:256:16)
at Query.run (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\mysql\query.js:68:18)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\sequelize.js:619:16
at async MySQLQueryInterface.insert (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\abstract\query-interface.js:748:21)
at async model.save (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\model.js:3954:35)
at async Function.create (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\model.js:2207:12)
at async module.exports.createOne (C:\Users\semer\Desktop\testing skills\toDoBlog\server\controllers\userController.js:6:16) {
parent: Error: Table 'todoblog.users' doesn't exist
at Packet.asError (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packets\packet.js:712:17)
at Prepare.execute (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\commands\command.js:28:26)
at Connection.handlePacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:425:32)
at PacketParser.onPacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:75:12)
at PacketParser.executeStart (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:82:25)
at Socket.emit (node:events:329:20)
at addChunk (node:internal/streams/readable:304:12)
at readableAddChunk (node:internal/streams/readable:279:9)
at Socket.Readable.push (node:internal/streams/readable:218:10) {
code: 'ER_NO_SUCH_TABLE',
errno: 1146,
sqlState: '42S02',
sqlMessage: "Table 'todoblog.users' doesn't exist",
sql: 'INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
parameters: [
'SEMER',
'semer',
'hash(info.password)',
'2021-03-04 16:57:41',
'2021-03-04 16:57:41'
]
},
original: Error: Table 'todoblog.users' doesn't exist
at Packet.asError (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packets\packet.js:712:17)
at Prepare.execute (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\commands\command.js:28:26)
at Connection.handlePacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:425:32)
at PacketParser.onPacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:75:12)
at PacketParser.executeStart (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:82:25)
at Socket.emit (node:events:329:20)
at addChunk (node:internal/streams/readable:304:12)
at readableAddChunk (node:internal/streams/readable:279:9)
at Socket.Readable.push (node:internal/streams/readable:218:10) {
code: 'ER_NO_SUCH_TABLE',
errno: 1146,
sqlState: '42S02',
sqlMessage: "Table 'todoblog.users' doesn't exist",
sql: 'INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
parameters: [
'SEMER',
'semer',
'hash(info.password)',
'2021-03-04 16:57:41',
'2021-03-04 16:57:41'
]
},
sql: 'INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
parameters: [
'SEMER',
'semer',
'hash(info.password)',
'2021-03-04 16:57:41',
'2021-03-04 16:57:41'
]
}
[nodemon] app crashed - waiting for file changes before starting...

How do i fix inserting to database with Sequelize Node Express Mysql?

I am trying to create a simple registration form which i will then proceed to other CRUD operations new to node js
I have created the mysql database and done the modelling and connection with Sequelize also i have created my view with pug and i did console.log for the entries from my form and everything is fine till it gets to database insert
var express = require('express');
var router = express.Router();
var Sequelize = require("sequelize");
var db = require('../src/database/connection');
var User = require('../src/model/User');
router.get('/', function(req, res, next){
res.render('signup');
});
router.post('/register', function(req, res, next){
let { username, useremail, pass, re_pass } = req.body;
let errors = [];
//checking feilds
if( !username || !useremail || !pass || !re_pass)
{
errors.push({msg: 'Please no field should be left empty'});
}
//checking Password
if(pass !== re_pass)
{
errors.push({msg: 'Passwords Dont Match'});
}
//check Password Length
if(pass.length < 7)
{
errors.push({msg: 'Passwords should be more than 7 characters '})
}
//reload page with contents if error encountered
if(errors.length > 0)
{
res.render('signup', {
errors,
username,
useremail,
pass,
re_pass
});
} else{
console.log(req.body);
User.create({
username,
useremail,
pass,
}).then(user => res.redirect('/register')).catch(err => console.log(err));
}
});
module.exports = router;
This is the error i am getting. PLEASE HELP
{ SequelizeValidationError: notNull Violation: User.email cannot be null,
notNull Violation: User.password cannot be null
at Promise.all.then (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\sequelize\lib\instance-validator.js:74:15)
at tryCatcher (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:512:31)
at Promise._settlePromise (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:569:18)
at Promise._settlePromise0 (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:694:18)
at Promise._fulfill (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:638:18)
at PromiseArray._resolve (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise_array.js:126:19)
at PromiseArray._promiseFulfilled (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise_array.js:144:14)
at Promise._settlePromise (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:574:26)
at Promise._settlePromise0 (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:694:18)
at _drainQueueStep (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:138:12)
at _drainQueue (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:131:9)
at Async._drainQueues (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:17:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
name: 'SequelizeValidationError',
errors:
[ ValidationErrorItem {
message: 'User.email cannot be null',
type: 'notNull Violation',
path: 'email',
value: null,
origin: 'CORE',
instance: [User],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: [] },
ValidationErrorItem {
message: 'User.password cannot be null',
type: 'notNull Violation',
path: 'password',
value: null,
origin: 'CORE',
instance: [User],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: [] } ] }
Seems like req.body is always empty
use body parser to put request body to req.body
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
Thanks to everyone that tried helping me solve this problem so my mistake was that i didnt point to the database rows in the create method so what i did was
User.create({
username: req.body.username,
email: req.body.useremail,
password: req.body.pass,
}).then(user => res.redirect('signup/register')).catch(err => console.log(err));
not
User.create({
username,
useremail,
pass,
}).then(user => res.redirect('/register')).catch(err => console.log(err));

Categories

Resources