Node.js express post parameters always undefined - javascript

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

Related

Cannot POST form - ExpressJS

I'm learing ExpressJS, i want to do the login part , but i gave me this
Cannot POST /login
im using the post method why it gave me this error
here a detailed post , thank you in advance for helping me
html part
<form method="POST">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" >
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password">
<button type="submit">Login</button>
</div>
</form>
The route.js
router.post('/login'),(req,res)=>{
var username= req.body.name;
var password = req.body.password;
con.query('SELECT * FROM authentication WHERE username = ?',username, function (error, results, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(results.length >0){
if(results[0].password == password){
res.send({
"code":200,
"success":"login sucessfull"
});
}
else{
res.send({
"code":204,
"success":"username and password does not match"
});
}
}
else{
res.send({
"code":204,
"success":"username does not exits"
});
}
}
});
}
module.exports = router
index.js
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
when trying to post this form i'm getting:
Cannot POST /login
what am i missing here?
You should handle current page, not '/login' page in route.js :
router.post('/', //...
Instead of writing
router.post('/login', //...
Because you sent the form data to the current page not to the '/login' page
Why current page ?
Because, you didn't define action attribute in your form
You need to define form action
<form action="/login" method="post">
But I recommend you to use js for sending requests
fetch('/login', {
method: 'POST',
body: JSON.stringify(yourFormData),
// ...another Opts if it needs
})
Also it can be problem with your server code because I don't see defining router in indexRouter file, you should add it:
const express = require('express');
const router = express.Router();
// then your code:
router.post('/login', loginController);
But you can add this line for check post requests:
app.post('/login', (req, res) => {
res.status(201).json(req.body); // or console.log
});

Nodejs post method - req.body.variable undefined

I have the following App.js:
var express = require('express'),
app = express(),
engines = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
bodyParser = require('body-parser')
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended : true }));
// app.use(bodyParser.urlencoded());
// app.use(bodyParser.json());
app.post('/insert_movie', function (req, res) {
var movieName = req.body.movie_name;
console.log(movieName);
});
// No route matching:
app.use(function (req, res) {
res.sendStatus(404);
});
var server = app.listen(3000, function () {
var port = server.address().port;
console.log('Express server listening on port %s.', port);
});
My html page:
<h1> Add new movies</h1>
<form action="/insert_movie" method="POST">
<input type="text" id="movie_name">
<input type="text" id="movie_year">
<input type="text" id="movie_imdb">
<input type="submit" value="Submit" />
</form>
When I enter values into the text boxes and press submit, my post method is hit ('/insert_movie'). However movieName is undefined not only that but req.body is {}
Can someone explain to me what I'm doing wrong here as I've gone through many solutions on this website however they're all pointing the body parser being incorrectly setup, I've tried the following:
app.use(bodyParser.urlencoded({ extended : true }));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
Neither of these fix my issue.
You need to add name attribute to the input elements. That's one of the things your body-parser library needs to parse the form.
<h1> Add new movies</h1>
<form action="/insert_movie" method="POST">
<input type="text" name="movie-name" id="movie_name">
<input type="text" name="movie-year" id="movie_year">
<input type="text" name="movie-url" id="movie_imdb">
<input type="submit" value="Submit" />
</form>
try to use this
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
limit: '500mb',
extended: true,
parameterLimit: 50000
}));
app.use(expressValidator());
app.use(bodyParser.json());
use multer middle ware for req.body
var app = require('express')();
var multer = require('multer);
var upload = multer().any();
//multer().any() upload both array and file
//add the multer middle ware in your router
app.post('/insert_movie',upload, function (req, res) {
var movieName = req.body.movie_name;
console.log(req.body);
console.log(movieName);
});
you can see the official npm blog
https://www.npmjs.com/package/multer

Express Server - Cannot POST / [duplicate]

This question already has answers here:
How to access POST form fields in Express
(24 answers)
Closed 7 years ago.
I recently followed a simple tutorial on how to build an Express server (https://codeforgeek.com/2014/06/express-nodejs-tutorial/).
I am trying to extend the code from this tutorial so that I can respond to post requests. I want to do this by updating a json file (that happens to be filled with 'user comments', and then rerendering at '/'
./server.js:
var express = require('express');
var app = express();
// routing configuration
require('./router/main')(app);
// ejs configuration
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// run the server
var server = app.listen(8080, function(){
console.log('Express server listening on port 8080');
});
./router/main.js (routers):
var fs = require('fs');
var ejs = require('ejs')
module.exports = function(app){
app.get('/', function(req, res){
var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json'));
res.render('index.ejs', comments);
});
app.post('/', function(req, res){
console.log('here in post');
var name = req.body.name;
var message = req.body.message;
var newComment = {"name": name, "message": message};
var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json'));
comments.push(newComment);
fs.writeFileSync(__dirname + '/../comments.json', comments, 'utf8');
//redirect to a 'get' on '/'
res.redirect('/');
});
app.get('/about', function(req, res){
res.render('about.html')
});
}
./views/index.ejs:
<div>
<div>
<h1> Joe's Forum </h1>
<a href='/about'> (about) </a>
</div>
<div>
<ul>
<% comments.forEach( function(comment){ %>
<li>
<%= comment.name %> : <%= comment.message %>
</li>
<% }); %>
</ul>
</div>
<h2> Enter a new comment </h2>
<form action='/' method="post">
Enter your name: <input type='text' name='name'> <br><br>
Enter your message: <input type='textarea' name='message'> <br><br>
<input type='submit' value='Submit'>
<form>
</div>
./comments.json:
{
"comments": [
{"name":"Joe", "message" : "What advantages does Node.js afford the web developer?"},
{"name": "John", "message": "Asynchronous IO helps us to keep our pages responsive even if the server is fetching data"}
]
}
When I try to submit a new comment from my form, all I see is this:
"Cannot POST /"
Can someone please explain why I might be getting this error? Thanks
There are actually a couple of problems, but the main one is that you don't have a body parser - the module that converts a node stream in the POST to a req.body. I am currently only familiar with bodyParser, and you should probably research that a bit. Although it is shown in Express 4.x documentation, you get a deprecation message when you run the server.
The other problem is the issue of comments.push. That should be comments.comments.push. The following works:
router.js:
var fs = require('fs');
var ejs = require('ejs')
module.exports = function(app){
app.get('/', function(req, res){
var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json'));
res.render('index.ejs', comments);
});
app.post('/', function(req, res){
console.log('here in post');
console.log(req.body)
var name = req.body.name;
var message = req.body.message;
var newComment = {"name": name, "message": message};
var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json'));
comments.comments.push(newComment);
fs.writeFileSync(__dirname + '/../comments.json', JSON.stringify(comments), 'utf8');
//redirect to a 'get' on '/'
res.redirect('/');
});
app.get('/about', function(req, res){
res.render('about.html')
});
}
and server.js:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded())
// routing configuration
require('./router/main')(app);
// ejs configuration
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// run the server
var server = app.listen(8080, function(){
console.log('Express server listening on port 8080');
})

cannot post form in node.js express

I am very much beginner with node.js.
There is a sample form with that I am trying to insert values in database-
Here is my test page-
<form action="/create" method="POST" class="form-horizontal" enctype="application/x-www-form-urlencoded">
<input type="text" id="username_input" name="username">
<input type="text" id="password_input" name="password">
<input type="submit" name="Submit" value="Insert" class="btn">
</form>
Trying to post it-
I created test.js file and writing post method in it-
exports.list = function (req, res) {
req.getConnection(function (err, connection) {
console.log(con)
app.post("/create", function (req, res) {
var username = req.body.username,
password = req.body.password;
console.log(username);
console.log(password);
connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {
if (error) {
console.log(error.message);
} else {
console.log('succes');
}
});
});
});
}
But this didn't work.
I tried writing post method in main server.js file also-
app.post("/create", function (req, res) {
var username = req.body.username,
password = req.body.password;
console.log(username);
console.log(password);
connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {
if (error) {
console.log(error.message);
} else {
console.log('succes');
}
});
});
but this didn't work also.
I am following current settings in server.js file-
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, index_form = require('./routes/index_form')
, user = require('./routes/user')
, test = require('./routes/test')
, mysql = require('mysql')
, http = require('http')
, path = require('path')
, mongoose = require('mongoose');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass#123'
});
var app =express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function () {
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/test', test.test);
app.get('/users', user.list);
app.get('/index_form', index_form.index_form)
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
Kindly guide me through this all , How do I make my form post with node.js?
Did you try putting app.post("/create", test.test); into your current server.js after your GET routes yet? Because what I saw here your current server.js does not have any POST request.

How to call a server side function from client side (e.g. html button onclick) in Node.js?

I need a complete basic example in Node.js of calling a server-side function from (client side) html button onclick event, just like in ASP.NET and C#.
I am new to Node.js and using the Express framework.
Any help?
IMPROVED QUESTION:
//server side :
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('views',__dirname + '/views');
app.set('port', process.env.PORT || 3000);
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'html');
app.use(app.router);
app.get("/",function(req,res)
{
res.render('home.html');
});
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
//Client Side
<input type="button" onclick="" /> <--just want to call the serverside function from here-->
Here's an example using Express and a HTML form.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.use(express.bodyParser());
app.post('/', function(req, res) {
console.log(req.body);
res.send(200);
});
server.listen(process.env.PORT, process.env.IP);
The code above will start an instance of Express, which is a web application framework for Node. The bodyParser() module is used for parsing the request body, so you can read post data. It will then listen for POST requests on the route /.
<form method="post" action="/">
<input type="test" name="field1">
<input type="test" name="field2">
<input type="submit">
</form>
And if you submit that form, in req.body for the route /, you will get the result:
{ field1: 'form contents', field2: 'second field contents' }
To run a function, just put it inside the POST handler like this:
var foo = function() {
// do something
};
app.post('/', function(req, res) {
console.log(req.body);
res.send(200);
// sending a response does not pause the function
foo();
});
If you don't want to use Express then you can use the native HTTP module, but you'd have to parse the HTTP request body yourself.
var http = require('http');
http.createServer(function(request, response) {
if (request.method === 'POST') {
var data = '';
request.on('data', function(chunk) {
data += chunk;
});
request.on('end', function() {
// parse the data
foo();
});
}
}).listen(80);

Categories

Resources