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
Related
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));
})
I'm learning about backend and I have a problem with csurf protection in my express nodejs project. When I submit in add-admin form is working find, but add-product form and edit-product form I receive the error
invalid csrf token
403
ForbiddenError: invalid csrf token
this is my app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(session);
var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var adminRouter = require('./routes/admin');
const Product = require('./models/product');
var app = express();
mongoose.connect('mongodb://localhost:27017/project3', {useNewUrlParser: true, useUnifiedTopology: true});
require('./config/passport')(passport);
// view engine setup
app.engine('.hbs',expressHbs({defaultLayout:'layout', extname:'.hbs', runtimeOptions: {
allowProtoPropertiesByDefault: true,
allowProtoMethodsByDefault: true
}}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
secret:'mysupersecret',
resave: false,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection}),
cookie: {maxAge: 30*60*24*60*1000}
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/static',express.static('public'));
app.use(function(req,res,next){
res.locals.login = req.isAuthenticated();
res.locals.session = req.session;
next();
});
//routes
app.use('/admin', adminRouter);
app.use('/user', userRouter);
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
My admin.js
var express = require('express');
var router = express.Router();
var csrf = require('csurf');
var multer = require('multer');
var mongoose = require('mongoose');
var async = require('async');
var {check, validationResult} = require('express-validator');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var csrfProtection = csrf();
router.use(csrfProtection);
mongoose.connect('mongodb://localhost:27017/project3', {useNewUrlParser: true, useUnifiedTopology: true});
var Product = require('../models/product');
var User = require("../models/user");
// add-product page
router.get("/add-product",csrfProtection,
function(req,res,next) {
var messages = req.flash('error');
res.render('admin/add-product', {
csrfToken: req.csrfToken(),
messages: messages,
hasErrors: messages.length>0,
});
});
//edit-product page
router.get("/edit-product/:id", csrfProtection,function(req,res,next){
Product.findById(req.params.id, function(err, data){
if(err) {
throw err;
} else {
res.render("admin/edit-product", {
csrfToken: req.csrfToken(),
editedProduct:data,
});
}
});
});
//delete a product
router.get("/delete-product/:id", function(req,res,next){
Product.deleteOne({_id: req.params.id}, function(err){
if(err) {
throw err;
} else {
res.redirect("../list-product");
}
});
});
//list admin
router.get('/list-admin', function(req,res,next){
User.find({rule: 2}, function(err,admin){
if(err) {
throw err;
}
else {
res.render('admin/list-admin', {
csrfToken: req.csrfToken(),
admin: admin
});
}
});
});
// add account admin
router.get('/add-admin', function(req,res, next) {
var messages = req.flash('error');
res.render('admin/add-admin', {
csrfToken: req.csrfToken(),
messages: messages,
hasErrors: messages.length>0
});
});
module.exports = router;
my add-user.hbs
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4 col-sm-offet-3">
<form action="/admin/add-product" method="post" id='checkout-form' enctype="multipart/form-data">
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="name">Tên sản phẩm</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
</div>
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit" class="btn btn-success">Thêm sản phẩm</button>
</form>
</div>
</div>
edit-product.hbs
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4 col-sm-offet-3">
<form action="../edit" method="post" id='edit-form' enctype="multipart/form-data" >
<div class="row">
<input type="hidden" name="IDChar" value={{editedProduct._id}}>>
<div class="col-xs-12">
<div class="form-group">
<label for="name">Tên sản phẩm</label>
<input type="text" id="name" value="{{editedProduct.name}}" class="form-control" required>
</div>
</div>
<hr>
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit" class="btn btn-success">Thay đổi</button>
</form>
</div>
</div>
add-admin.hbs
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h3>Thêm tài khoản admin</h3>
{{#if hasErrors}}
<div class="alert alert-danger">
{{#each messages}}
<p>{{this}}</p>
{{/each}}
</div>
{{/if}}
<form action="/admin/add-admin" method='post'>
<div class="form-group">
<label for="email">Email</label>
<input type="text" id ="email" name = "email" class="form-control">
</div>
<div class="form-group">
<label for="password">Mật khẩu</label>
<input type="password" id="password" name="password" class="form-control">
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit"class="btn btn-primary">Thêm tài khoản Admin</button>
</form>
</div>
</div>
i searched in google and document of csurf but i can't find resolve. Please help me, thank you for watching.
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
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");
});
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">