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

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

Related

Javascript / EJS Code showing error : TypeError: Cannot read properties of null (reading 'name')

The code does run at first but the moment I submit my first post request, it gives the following error :
node:events:504
throw er; // Unhandled 'error' event
^
TypeError: Cannot read properties of null (reading 'name')
Currently using : Node.js, mongoose
Packages used : express, bodyParser, ejs, Mongoose
JS file code :
const express = require("express");
const app = express();
app.use(express.static("public"));
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
const ejs = require("ejs");
app.set("view engine", "ejs");
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/learndb");
const questionSchema =
{
question : String,
answer : String
};
const Question = mongoose.model("Question", questionSchema);
const subjectSchema =
{
name : String,
questions : [questionSchema]
};
const Subject = mongoose.model("Subject", subjectSchema);
app.post("/", function(req, res)
{
const subjectName= req.body.subjectName;
const subject = new Subject({ name: subjectName});
subject.save();
res.redirect("/");
});
app.get("/", function(req, res)
{
Subject.find({}, function(err, foundSubjects)
{
res.render("home", {whichSubjects: foundSubjects});
});
});
HTML/EJS File code:
<body>
<h1>Choose a Subject</h1>
<% whichSubjects.forEach(function(eachSubject) { %>
<div class="">
<form class="" action="/<%=eachSubject.name%>" method="get">
<button type="submit" name="button"> <%=eachSubject.name%></button>
</form>
</div>
<% }) %>
<div class="">
<form class="" action="/" method="post">
<input type="text" name="subjectName" value="">
<button type="submit" name="button">Add A Subject</button>
</form>
</div>
</body>
The answer was so simple but we missed it. The first thing wrong in your code are the paths. You have two paths named /. You want to make your home route the place your visualize all the data and then make a form that posts the data to a different route and upon success, should redirect to your home route. In your case all you have to do is change the post route on the hmtl to /addsubject and on the js file to app.post('/addsubject' rest of code
//Generate express app
const express = require('express');
const app = express();
app.set('views', './views');
app.set('view engine', 'ejs');
//Generate body parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Connect to MongoDB
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/learndb');
const subJectSchema = new mongoose.Schema({
name: String,
questions: [{type: String}]
})
const Subject = mongoose.model('Subject', subJectSchema);
app.post('/addsubject', (req, res) => {
const subjectName = req.body.subjectName;
const subject = new Subject({ name: subjectName });
subject.save((err, subject) => {
if (err) {
console.log(err);
} else {
console.log("User Saved");
}
});
res.redirect('/');
});
app.get('/', (req, res) => {
Subject.find({}, (err, subjects) => {
if (err) {
console.log(err);
} else {
res.render('home', { subjectList: subjects });
}
});
});
app.listen(4000, () => {
console.log('Server started on port 3000');
});
<body>
<h1>Choose Subject</h1>
<div>
<form action="/addsubject" method="post">
<label for="name">Name</label>
<input type="text" name="subjectName" id="name">
<input type="submit" value="Create Subject">
</form>
</div>
<% if(subjectList.length> 0){ %>
<% subjectList.forEach(subject=>{ %>
<p>
<%= subject.name %>
</p>
<% }) %>
<% } else { %>
<p>No subjects found Add Some</p>
<% } %>
</body>

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

Cannot read property 'task' of undefined

enter image description hereI never faced this problem before but now "req.body.task" is not working and I don't know why its happening.
Here's the form
<form action="/" method="POST">
<div class="input-box">
<input type="text" name="task" id="" class="input-add">
<button type="submit" name="button" class="btn-add">+</button>
</div>
</form>
Here's the post request
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.set(bodyParser.urlencoded({extended: false}));
app.use(express.static("public"));
let items = [];
app.get("/", (req,res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/", (req,res) => {
const item = req.body.task;
console.log(item);
});
app.listen(3000, () => {
console.log("Server running at port 3000");
});
This
app.set(bodyParser.urlencoded({extended: false}));
should be
app.use(bodyParser.urlencoded({extended: false}));
BodyParser is a middleware and should be used using app.use methods.
See the docs for more details
app.set is used to set values to app variables, for example view engines

404 Error while saving data to mongoDb from node.js & express

im currently trying to save some data from Bootstrap input fields into my mongoDB database but i always get the error insertMovie:1 POST http://localhost:3000/insertMovie 404 (Not Found). I tried to change the Routes but i cant find my mistake. My Schema is in a file called movie.js.
I Feel like i dont really get the Route thing of express, im very new at this.
<div class="container">
<div class="row">
<div class="col">
<form method="post" action="/insertMovie">
<h1 class="text-center pt-5">Neuen Film anlegen</h1>
<div class="form-group">
<label>Titel</label>
<input
type="text"
class="form-control"
placeholder="Titel eingeben"
name="title"
/>
</div>
<div class="form-group">
<label>Beschreibung</label>
<input
type="text"
class="form-control"
placeholder="Beschreibung eingeben"
name="description"
/>
</div>
<div class="form-group">
<label>Startdatum</label>
<input
type="text"
class="form-control"
placeholder="Startdatum eingeben"
name="start"
/>
</div>
<div class="form-group">
<label>Aktuell laufend</label>
<input
type="text"
class="form-control"
placeholder="Beschreibung eingeben"
name="currentlyRunning"
/>
</div>
<input id="submit" type="submit" class="btn btn-primary" />
</form>
</div>
</div>
</div>
movies.js
const express = require("express");
const router = express.Router();
const Movie = require("../models/movie");
router.get("/", async (req, res) => {
try {
const movies = await Movie.find();
res.json(movies);
} catch (err) {
res.json({ message: err });
}
});
router.post("/insertMovie", async (req, res) => {
const movie = new Movie({
title: req.body.title,
description: req.body.description,
start: req.body.start
});
try {
const savedMovie = await movie.save();
res.json(savedMovie);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
app.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
//Middlewares
app.use(bodyParser.json());
app.use(cors());
//Import Routes
const moviesRoute = require("./routes/movies");
app.use("/movies", moviesRoute);
// include a static file serving middleware
app.use(express.static(__dirname + "/"));
// Get all Data
app.get("/data", function(req, res) {
res.sendfile("index.html");
});
// Insert new Movie
app.get("/insertMovie", function(req, res) {
res.sendfile(__dirname + "/insert.html");
});
mongoose.connect("mongodb://localhost:27017/testDB", { useNewUrlParser: true });
app.listen(3000);
The issue here is with your movie routes. With the way you set it up, your endpoint is actually:
localhost:3000/movies/insertMovie
but you are using:
localhost:3000/insertMovie

Express req.body undefined when passing to user model

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">

Categories

Resources