Express req.body undefined when passing to user model - javascript

Using Express 4.14 I have a simple html form accepting username and password. I want to pass that info to a function that inserts it into my psql database. But first I verify if that user is already in the db. I keep getting the error at "let uname = req.body.name;"
Thanks for the help.
HMTL form:
<div>
<form class="" action="/register" method="post">
<input class="text-input" type="text" name="user[username]" value="" placeholder="Username">
<input class="text-input" type="password" name="user[password]" value="" placeholder="Password">
<input type="submit" value="Sign up">
</form>
</div>
my function to insert into db:
verifyUser(req, res, next) {
let uname = req.body.name;
db.any(`SELECT * FROM users WHERE name = uname LIMIT 1`)
.then(() => {
next();
})
my server setup:
'use strict'
require('dotenv').config({ silent: true });
const bodyParser = require('body-parser');
const express = require('express');
const logger = require('morgan');
const path = require('path');
const app = express();
const authRouter = require('./routes/auth/auth.js');
const loginRouter = require('./routes/login/login.js');
const apiRouter = require('./routes/api/apiRoute.js');
const profileRouter = require('./routes/profile/profile.js');
const regRouter = require('./routes/register/register.js');
const PORT = process.argv[2] || process.env.port || 3000;
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.listen(PORT, () => { console.log('app is listening on 3k')});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public/landing.html'));
});
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'public/login.html'));
});
app.get('/signup', (req, res) => {
res.sendFile(path.join(__dirname, 'public/signup.html'));
});
app.use('/api', apiRouter);
app.use('/auth', authRouter);
app.use('/login', loginRouter);
app.use('/register', regRouter);
app.use('/profile', profileRouter);
regRouter: None of those console.logs actually return anything. So, there's that.
const regRouter = require('express').Router();
const { createUser } = require('../../models/user_model');
regRouter.get('/', (req, res) => {
console.log('register line 5')
res.render('register');
});
regRouter.post('/', createUser, (req, res) => {
console.log('register line 10')
res.render('landing');
});
module.exports = regRouter;
createUser:
function createUser(req, res, next) {
console.log('create user line 10');
let uname = req.body.name;
console.log('body', req.body);
let encryption = bcrypt.hashSync(req.body.password, SECRET);
db.any(`INSERT INTO users
(name, password)
VALUES ($1, $2);` [uname, encryption])
.then(() => {
next();
})
.catch(error => next(error));
};

In your html there isn't any input field with name attribute set to "name" or "password.
<input class="text-input" type="text" name="name" value="" placeholder="Username">
<input class="text-input" type="password" name="password" value="" placeholder="Password">

Related

Can't create new document on POST (mongoose/express)

Check My Node.js code Please I want to Save Contact page data in mongoose compass this don't throw any error but also not saving data
<form action="/" class="contact_form grid" method="POST">
HTML IS TOTALLY CORRECT WRITTEN I THINK PLEASE TELL ME WHATS WRONG IN THIS APP.JS CODE
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const bodyparser = require('body-parser')
const path = require('path');
mongoose.connect('mongodb://localhost:27017/ContactPage');
const port = 3000;
var contactSchema= new mongoose.Schema({
name:{type:String},
email:{type:String},
project:{type:String},
message:{type:String}
});
var Contact = mongoose.model('Contact', contactSchema);
module.exports = Contact;
app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded({extended: true}))
app.set('view engine', 'ejs');
app.get('/', function(req,res){
res.sendFile(path.join(__dirname, "index.html"))
});
app.post('/',(req,res)=>{
var myData = new Contact(req.body);
myData.save().then(()=>{
res.send(req.body)
}).catch(()=>{
res.status(400).send(req.body);
});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Check My Node.js code Please I want to Save Contact page data in mongoose compass this don't throw any error but also not saving data
<form action="/" class="contact_form grid" method="POST">
<div class="contact_inputs grid">
<div class="contact_content">
<label for="" class="contact_label">Name</label>
<input type="text" name= "name" class="contact_input">
</div>
<div class="contact_content">
<label for="" class="contact_label">Email</label>
<input type="email"name="email" class="contact_input">
</div>
</div>
<div class="contact_content">
<label for="" class="contact_label">Project</label>
<input type="text" name="project" class="contact_input">
</div>
<div class="contact_content">
<label for="" class="contact_label">Message</label>
<textarea name="" id="" cols="0" rows="7" name = "message" class="contact_input"></textarea>
</div>
<div>
<a href="" class="button button--flex">
Send Message
<i class="fas fa-paper-plane button_icon"></i>
</a>
</div>
</form>
#1 you are not submitting from HTML, so instead of:
<div>
<a href="" class="button button--flex">
Send Message
<i class="fas fa-paper-plane button_icon"></i>
</a>
</div>
write:
<button type="submit">
Send Message
</button>
#2 express improvements
contactSchema file:
const mongoose = require('mongoose')
var contactSchema = new mongoose.Schema({
name: { type: String },
email: { type: String },
project: { type: String },
message: { type: String }
});
module.exports = mongoose.model('Contact', contactSchema);
app file:
const express = require('express');
const mongoose = require('mongoose');
const bodyparser = require('body-parser')
const path = require('path');
const port = 3000;
const app = express();
app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded({ extended: true }))
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, "index.html"))
});
app.post('/', (req, res) => {
var { name, email, project, message } = req.body;
var myData = new Contact({
name,
email,
project,
message,
});
myData.save().then((newData) => {
res.send(newData)
}).catch((err) => {
res.status(400).send("Error: ", err, " , Data: ", req.body);
});
});
app.listen(port, () => {
mongoose.connect('mongodb://localhost:27017/ContactPage')
.then(() => console.log("Server & DB listening at http://localhost:${port}"))
.catch(err => console.log(err));
})

Cannot read property 'username' of undefined...something to do with body-parser

I need to log the username from the file register.ejs to my console
i have checked the code soo many times and i couldn't get the solution the is error.. plz help me out
this is my /register file:
<!-- Makes POST request to /register route -->
<form action="/register" method="POST">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-dark">Register</button>
</form>
</div>
</div>
</div>
This is my app.js file:
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.set("view engine", "ejs");
app.use(express.static("publica"));
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/userDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const userSchema = new mongoose.Schema({
email: String,
password: String,
});
const User = mongoose.model("User", userSchema);
app.get("/", (req, res) => {
res.render("home");
});
app.get("/login", (req, res) => {
res.render("login");
});
app.get("/register", (req, res) => {
res.render("register");
});
app.post("/register", function (req, res) {
console.log(req.body.username);
});
app.listen(3000, () => {
console.log("All Good Bruh!!!");
});
im trying to log the username from /register page but im getting this error:
Cannot read property 'username' of undefined
Please help me out
add app.use(bodyParser.urlencoded({ extended: true }));
some where up

how to solve "Cannot PUT /"

I am trying to update local database in mongodb. In my project I want to update my data here is the code.
second part is the edit part that i use to redirect my update data. It don't show any error so i can not find any problem to fix.All project in node.js, and use handelbar template , mongoose as database
:
const express = require('express')
const app = express()
const exphbs = require('express-handlebars');
const mongoose = require('mongoose')
const path = require('path')
const Idendity = require('./db/db.js')
const methodOverride = require('method-override')
app.use(methodOverride('_method'))
app.use(express.static( __dirname + "/public"));
app.use(express.urlencoded({
extended: false
}))
app.engine('.hbs', exphbs({
extname: '.hbs'
}))
app.set('view engine', '.hbs')
async function connectDB() {
try {
await mongoose.connect('mongodb://localhost:27017/Idendity', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
console.log('database is connected')
} catch (error) {
console.log(error)
}
}
connectDB()
app.get('/', async (req, res) => {
const idendity = await Idendity.find()
const idendities = {
data: idendity.map(element => {return{id:element._id,name:element.name,email:element.email,profession:element.profession}} )
}
//console.log(idendities.data)
res.render('home', {
ID: idendities.data,
title: 'Contact App'
})
})
app.post('/', async (req, res) => {
const idendity = new Idendity({
...req.body
})
await idendity.save()
res.redirect('/')
})
app.get('/edit/:id',async (req,res)=>{
const id = req.params.id
const idendity = await Idendity.findById(id)
const contex = {name:idendity.name,email:idendity.email,profession:idendity.profession}
if(idendity){
res.render('edit',{
idendity:contex
})
}else{
res.send('404 not found')
}
})
app.put('/edit/:id',async (req,res)=>{
const id = req.params.id
const value = req.body
const newIdendity = await Idendity.findByIdAndUpdate(id,value,{ useFindAndModify:false})
console.log(value)
if(newIdendity){
res.redirect(`/edit/${id}`)
}else{
res.send('404 not found')
}
})
app.listen(8000, () => {
console.log('port is listening')
})
//////////////////////////////////////////////////////
<div class="container">
{{#with idendity}}
<form action="/?_method=PUT" method="POST">
<label for="name">name</label><br>
<input type="text" name="name" id="name" value={{name}}><br>
<label for="email">email</label><br>
<input type="text" name="email" id="email" value={{email}}><br>
<label for="profession">profession</label> <br>
<input type="text" name="profession" id="profession" value={{profession}}><br>
<button class="btn btn-primary my-3">add</button>
</form>{{/with}}
cancel
</div>
you can send put request to the given route because you don't have any put method attached to that route you are trying to access.
you have to have an
app.put("/",async(req,res)=>{
//code
})
or you can use
// this will be accessible by all HTTP methods
app.use("/",async(req,res)=>{
//code
})
in your code to be able to send a put request to the server.

using simple node app, localhost not sending data

I'm a newbie so be kind. I've been trying to learn passport via an online tutorial (this one, github here) and as far as I can tell I've recreated the code verbatim but I'm getting an error that the localhost didn't send any data. My full code is here. I'm pasting some code below but I'm honestly unsure which piece of code to post since I don't know where the error is occurring.
Here's the server app:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
//Init app
var app = express();
//View engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
//body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
//set static folder
app.use(express.static(path.join(__dirname, 'public')));
//express session middleware
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//passport init
app.use(passport.initialize());
app.use(passport.session());
//validator middleware-- this code is straight from the validator github page
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split(',')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
//connect flash middleware
app.use(flash());
//global variables for flash messages
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
//set port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function() {
console.log('Server started on port ' + app.get('port'));
});
Here's the form:
<h2 class="page-header">Register</h2>
<form method="post" action="/users/register">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" name="name">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" placeholder="Email" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" placeholder="Password" name="password2">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
And here's the user js:
var express = require('express');
var router = express.Router();
//register
router.get('/register', function(req, res) {
res.render('register');
});
//login
router.get('/login', function(req, res) {
res.render('login');
});
//register user
router.post('/register', function(req, res) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
});
module.exports = router;
First things first: you are actually not doing anything on the post('/register'..)
You should save your model and return it if successful, something like this:
var schema = new mongoose.Schema({ name: 'string', email: 'string' });
var User = mongoose.model('User', schema);
//register user
router.post('/register', function(req, res) {
var name = req.body.name;
var email = req.body.email;
var user = new User({ name: name, email: email});
user.save(function (err) {
if (err) throw err;
res.send(user);
});
});
Of course you would define your model on a separate folder and import it to where it fits.

Save information to MongoDB database from form?

I want to save the information captured from an html form in a MongoDB database, I have the following code:
<!DOCTYPE html>
<html>
<head>
<title>Intro to Node and MongoDB</title>
</head>
<body>
<h1>Into to Node and MongoDB</h1>
<form method="post" action="/addname">
<label>Enter Your Name</label><br>
<input type="text" name="firstName" placeholder="Enter first name..." required>
<input type="text" name="lastName" placeholder="Enter last name..." required>
<input type="submit" value="Add Name">
</form>
</body>
</html>
And the following javascript code would be my app.js
var express = require("express");
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var mongoose = require("mongoose");
/*
mongoose.Promise = global.Promise;mongoose.connect("mongodb://localhost:27017/node-demo");
*/
var promise = mongoose.connect('mongodb://localhost:27017/node-demo', {
useMongoClient: true,
/* other options */
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/addname", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
Apparently the post request is working, filling in the fields and pressing the input type submit, however when checking the database is empty, just as it was when it was created. Does anyone know why I do not save the information?
I run your code here and the app.post was not called. It's because you're using app.use to send the index.html. app.use is used to bind middleware to your application. Instead, you should use app.get, which tells express to listen for requests to / and run the function when it sees one.
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});

Categories

Resources