Cannot GET node js error - javascript

I can't figure out where I missed to add something. I get the following error: Cannot GET /portal/destroybox/5797318673cf3f581163455c when I click on delete or update icons in portal.ejs:
(createbox in portal.ejs works and creates the item and stores it in the db, and then I forEach in the table to show all items with update and delete icons behind each item. Also the // todo test part in server.js is for another part of my app and that works, nothing to do with the portal/box part. I also do not have route in server.js for createbox, but that part works, so why do I need it for destroybox if I need it at all?)
portal.ejs
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Vm</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<% boxes.forEach( function ( box ){ %>
<tr>
<td>
<%= box.box_name %>
</td>
<td>
<%= box.vm %>
</td>
<td>
<a class="fa fa-wrench" aria-hidden="true" href="/portal/editbox/<%= box._id %>" title="Update this box"></a>
</td>
<td>
<a class="fa fa-trash-o" aria-hidden="true" href="/portal/destroybox/<%= box._id %>" title="Destroy this box"></a>
</td>
</tr>
<% }); %>
</tbody>
</table>
<p>
<strong>Add new box to `available boxes`</strong>
<br>
</p>
<form action="/createbox" method="post">
<div class="form-group">
<label>Box name</label>
<input type="text" class="form-control" name="box_name">
</div>
<div class="form-group">
<label>VM</label>
<input type="text" class="form-control" name="vm">
</div>
<div class="form-group">
<label>Description</label>
<input type="text" class="form-control" name="description">
</div>
<button type="submit" class="btn btn-warning btn-lg">Add box</button>
</form>
server.js
// server.js
// set up ======================================================================
// get all the tools we need
// mongoose setup
var db = require('./config/database.js');
require('./app/models/db');
require('./app/models/box');
var express = require('express');
var http = require('http');
var path = require('path');
var engine = require('ejs-locals');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var static = require('serve-static');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var session = require('express-session');
var routesindex = require('./routes/index');
//var routesbox = require('./routes/boxi');
// configuration ===============================================================
mongoose.connect(db.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.engine('ejs', engine);
app.use(logger('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({
secret: 'secretkeykeykeykey'
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
var routes = require('./app/routes/routes')(app, passport); // load our routes and pass in our app and fully configured passport
// todo test
app.use(routesindex.current_user);
app.get('/ind', routesindex.ind);
app.post('/ind/create', routesindex.create);
app.get('/ind/destroy/:id', routesindex.destroy);
app.get('/ind/edit/:id', routesindex.edit);
app.post('/ind/update/:id', routesindex.update);
app.use(static(path.join(__dirname, 'public')));
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
routes.js
// =====================================
// PORTAL ==============================
// =====================================
// show the signup form
app.get('/portal', isLoggedIn, function (req, res) {
var user_id = req.cookies ?
req.cookies.user_id : undefined;
Box.
find({
user_id: user_id
}).
sort('-updated_at').
exec(function (err, boxes) {
if (err) return next(err);
res.render('portal', {
boxes: boxes
});
});
});
app.post('/createbox', isLoggedIn, function (req, res) {
new Box({
user_id: req.cookies.user_id,
box_name: req.body.box_name,
vm: req.body.vm,
description: req.body.description,
updated_at: Date.now()
}).save(function (err, box, count) {
if (err) return next(err);
res.redirect('/portal/');
});
});
app.get('/destroybox/:id', isLoggedIn, function (req, res) {
Box.findById(req.params.id, function (err, box) {
var user_id = req.cookies ?
req.cookies.user_id : undefined;
if (box.user_id !== user_id) {
return utils.forbidden(res);
}
box.remove(function (err, box) {
if (err) return next(err);
res.redirect('/portal/');
});
});
});
app.get('/editbox/:id', isLoggedIn, function (req, res) {
var user_id = req.cookies ?
req.cookies.user_id : undefined;
Box.
find({
user_id: user_id
}).
sort('-updated_at').
exec(function (err, boxes) {
if (err) return next(err);
res.render('editbox', {
title: 'Vagrant Box',
boxes: boxes,
current: req.params.id
});
});
});
app.post('/updatebox/:id', isLoggedIn, function (req, res) {
Box.findById(req.params.id, function (err, box) {
var user_id = req.cookies ?
req.cookies.user_id : undefined;
if (box.user_id !== user_id) {
return utils.forbidden(res);
}
box.box_name = req.body.box_name;
box.vm = req.body.vm;
box.description = req.body.description;
box.updated_at = Date.now();
box.save(function (err, box, count) {
if (err) return next(err);
res.redirect('/portal/');
});
});
});

Because you don't have routes for that as the error states:
app.get('/destroybox/:id'
You can see you have a route from root / to destroybox then :id etc. While you are having a href of:
href="/portal/destroybox/<%= box._id %>"
from root / to portal and then destroybox then the id. Which is no where defined in the config.
Solution is to change the href to:
href="/destroybox/<%= box._id %>"
same goes for other href attributes too.

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>

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.

node.js Cannot read property 'collection' of undefined routes\index.js:6:11

I am a begginer at node.js and trying to build a basic todo list but keep getting the error:
Cannot read property 'collection' of undefined.
Can someone please explain what im doing wrong and how to I can get my get post requests working?
Thanks for the help !
routes/index.js
var express = require('express');
var router = express.Router();
var ObjectId = require('mongodb').ObjectId
// Get Homepage
router.get('/', ensureAuthenticated, function(req, res){
req.db.collection('Todo').find().sort({"_id": -1}).toArray(function(err, result) {
//if (err) return console.log(err)
if (err) {
req.flash('error', err)
res.render('index', {
title: 'User List',
data: ''
})
} else {
// render to views/user/list.ejs template file
res.render('index', {
title: 'User List',
data: 'ldld'
})
}
})
})
function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
} else {
//req.flash('error_msg','You are not logged in');
res.redirect('/users/login');
}
}
module.exports = router;
routes/Todo.js
// list dependencies
var express = require('express');
var router = express.Router();
// add db & model dependencies
var mongoose = require('mongoose');
var Todo = require('../models/Todo');
// interpret GET /products - show product listing */
// GET intepret GET /products/edit/:id - show single product edit form */
router.get('/Todo/edit/:id', function (req, res, next) {
//store the id from the url in a variable
var id = req.params.id;
var user_id = req.cookies ?
req.cookies.user_id : undefined;
//use the product model to look up the product with this id
Todo.findById(id,user_id, function (err, product) {
if (err) {
res.send('Product ' + id + ' not found');
}
else {
res.render('edit', { Todo: Todo });
}
});
});
// POST /products/edit/:id - update selected product */
router.post('/Todo/edit/:id', function (req, res, next) {
var id = req.body.id;
var Todo = {
_id: req.body.id,
content: req.body.content,
todos : todos,
updated_at : Date.now()
};
Todo.update({ _id: id}, content, function(err) {
if (err) {
res.send('Product ' + req.body.id + ' not updated. Error: ' + err);
}
else {
res.statusCode = 302;
res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
res.end();
}
});
});
// GET /products/add - show product input form
router.get('/Todo/create', function (req, res, next) {
res.render('add');
});
// POST /products/add - save new product
router.post('/Todo/create', function (req, res, next) {
// use the Product model to insert a new product
Todo.create({
content: req.body.content,
user_id:req.cookies.user_id,
updated_at : Date.now()
}, function (err,Todo) {
if (err) {
console.log(err);
res.render('error', { error: err }) ;
}
else {
console.log('Product saved ' + Todo);
res.render('added', {Todo: Todo.content });
}
});
});
// API GET products request handler
router.get('/api/Todo', function (req, res, next) {
Todo.find(function (err, products) {
if (err) {
res.send(err);
}
else {
res.send(Todo);
}
});
});
/* GET product delete request - : indicates id is a variable */
router.get('/Todo/delete/:id', function (req, res, next) {
//store the id from the url into a variable
var id = req.params.id;
//use our product model to delete
Todo.remove({ _id: id }, function (err,Todo) {
if (err) {
res.send('Product ' + id + ' not found');
}
else {
res.statusCode = 302;
res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
res.end();
}
});
});
// make controller public
module.exports = router;
views/index.handelbars
<h2 class="page-header">Dashboard</h2>
<p> Hello {{user.name}}
<p>Welcome to your dashboard</p>
<% layout( 'layout' ) -%>
<h1 id="page-title">{{ title }}</h1>
<div id="list">
<form action="/create" method="post" accept-charset="utf-8">
<div class="item-new">
<input class="input" type="text" name="content" />
</div>
</form>
{{#each todo}}
<div class="item">
<a class="update-link" href="/edit/{{#todo._id }}" title="Update this todo item">{{todo.content}}</a>
<a class="del-btn" href="/destroy/{{ #todo._id }}>" title="Delete this todo item">Delete</a>
</div>
{{/each }}
app.js
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');
var Todo = require('./routes/Todo');
// 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');
// BodyParser 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
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
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
app.use(flash());
// Global Vars
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);
app.use('/Todo', Todo);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
Add the following to your app.js, right after var app = express();
app.use(function (req, res, next) {
req.db = db;
next();
});
This will create a reference to your mongoose connection in all the incoming requests, accessible via req.db.

Nodejs : callback is not a function

In the below code , I am authenticating username and password user enters with the details from my mongo database . If successful , redirect to /main route (index.ejs) . I am getting error :- callback is not a function .
I am new to nodejs . I can't figure out where and why I am getting this error .
app.js
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var urlencoder = bodyParser.urlencoded({extended : true});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://<username>: <password>#ds141434.mlab.com:41434/teacherspro'; // using mLab
app.set('view engine' , 'ejs'); // ejs as view engine
var index = require('./routes/index'); // providing routes
var users = require('./routes/users');
app.set('views', path.join(__dirname, 'views'));
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/main', index);
app.use('/users', users);
app.get('/login' , function(req,res,next){ // rendering homepage
console.log('\r');
res.render('login'); // rendering login.ejs
console.log('rendered master page!');
next();
});
MongoClient.connect(url , function(err,db){
if (err) return;
app.post('/login' , urlencoder , function(req,res,next){
app.use(bodyParser.json());
var UserName = req.body.UserName;
var Password = req.body.Password;
db.collection('project1').find({ '$and' : [ {"UserName" : UserName} , {"Password" : Password} ]} , {_id : 0}).forEach(function(pes){ // authenticating username and password
if(true)
{
console.log(pes);
res.redirect('/main');
}
});
});
db.close();
next();
});
app.listen(5050);
module.exports = app;
Index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
MongoClient.connect(url , function(err,db){
if (err) return;
db.collection('project1').find({"UserName" : "karan"} , {_id : 0}).forEach(function(pes){
console.log(pes);
res.render('index', {Name : pes});
});
});
});
module.exports = router;
login.ejs
<form id = 'login' method = POST action = '/login'>
<label for = 'Username'> UserName </label>
<input type = 'text' name = 'UserName' value = ''>
<br />
<label for = 'Password'> Password </label>
<input type = 'password' name = 'Password' value = ''>
<br />
<center> <input type ="submit" value = "submit" /> </center>
<br />
</form>
Post callback has the following form:
app.post(path, callback);
Check the docs. app.post
Just remove urlencoder param.

Node.js express post parameters always undefined

I am pretty new to Node.js development, and I am aware that there are several stack overflow questions like this already, unfortunately none seem to fix my problem. So I feel all I can do is ask my question
So I am use Node.js with Express and the Jade view engine.
I based some of my code on this article : http://howtonode.org/express-mongodb
Anyway here is what I have
The node app :
var express = require('express');
var home = require('./routes/home');
var d3demo = require('./routes/d3demo');
var PersonProvider = require('./public/javascripts/personProvider').PersonProvider;
var personProvider = new PersonProvider('localhost', 27017);
var LinkProvider = require('./public/javascripts/linkProvider').LinkProvider;
var linkProvider = new LinkProvider('localhost', 27017);
var http = require('http');
var path = require('path');
var app = express();
//=============================================================================
// EXPRESS SETUP
//=============================================================================
app.configure(function(){
app.set('port', process.env.PORT || 2000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
//app.use(require('connect').bodyParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function () {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
//=============================================================================
// ROUTING
//=============================================================================
app.get('/home', function (req, res) {
home.homeGet(req, res, commonHelper, personProvider, linkProvider);
});
app.post('/home', function (req, res) {
home.homePost(req, res, personProvider);
});
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
and this is the Home route
/*
* GET home page.
*/
exports.homeGet = function(req, res, commonHelper, personProvider, linkProvider){
commonHelper.seedData(personProvider, linkProvider, function() {
res.render('home');
});
};
exports.homePost = function (req, res, personProvider) {
var newUserEmail = req.body.email;
console.log(req.body.length);
//console.log(x);
//var email = req.param('Email');
console.log("/Home posted Email :" + newUserEmail);
personProvider.save({
//email: req.param('Email'),
email: newUserEmail,
}, function (error, docs) {
if(error == null) {
res.redirect('/d3demo');
} else {
res.render('home');
}
});
};
And this is the jade view
extends layout
block head
link(rel='stylesheet', href='/stylesheets/home.css')
script(src='/javascripts/home.js')
block content
form(method='post', id='homeForm', action='http://localhost:2000/home')
div(id='dialog', title='error', style='display:none;')
p You need to supply a valid email
div(id='NewDetailsArea')
p Enter your email address, and then click enter
| <input type="text" id="email" class="email"></input>
div#homeSubmit
input(type='submit', value='Enter', id='enterEmail')
Which gets rendered to this
<form method="post" id="homeForm" action="http://localhost:2000/home">
<div id="dialog" title="error" style="display:none;">
<p>You need to supply a valid email</p></div>
<div id="NewDetailsArea">
<p>Enter your email address, and then click enter </p>
<input type="text" id="email" class="email">
</input><div id="homeSubmit"><input type="submit" value="Enter" id="enterEmail">
</div>
</div>
</form>
So the problem:
Well the problem is actually pretty simply. Within the function
homePost = function (req, res, personProvider)
I would like to be able to get the value of the 'email' form field
I have tried req.param('email'), req.body.email I have tried the standard express.bodyParser() and also the connect (which someone mentioned in another answer) one require('connect').bodyParser(), but alas all I get is undefined.
Also if I try and console.log(req.body) I get undefined
What am I doing wrong?
You need to supply a name attribute for the email input. The name is what gets sent when the form is submitted:
<input type="text" id="email" name="email" class="email">

Categories

Resources