login.html(I have converted it to jade) is my login page which is opened at localhost:3000.
I send the form details to index.js(server).
Problem:
On console.log(username) I get output as undefined. Please help.
Have I used body-parser correctly ?
var express= require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
app.use(express.static('./Public'));
app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
app.get("/", function(req, res){
res.render("login");
});
app.use(bodyParser.urlencoded({
extended : false
}));
app.use(bodyParser.json());
app.post('/', function(req,res) {
var username = req.body.name;
console.log(username);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
html code: (login.html)
<html>
<body>
<form action="/" method="post" enctype="multipart/form-data">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<br />
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email address" />
<br />
<input type="submit" value="Create Profile" />
</fieldset>
</form>
<script>
var socket = io.connect("http://loacalhost:3000");
</script>
</body>
</html>
If you look documentation of body-parser you can notice this:
This does not handle multipart bodies, due to their complex and
typically large nature. For multipart bodies, you may be interested in
the following modules:
busboy and connect-busboy multiparty and connect-multiparty formidable
multer
So you have to either change enctype="multipart/form-data" to for example enctype="application/json" or to use some other module.
Hope that I have helped you.
Related
Im using express, node, bodyParser to pull information from a contact form and post it to the terminal. When I run the code and access my demo site through LocalHost:3000, upon submitting, my input items are not showing up in the terminal.
I've tried changing the form attributes action="send" action="/send" action="/"
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const nodemailer = require('nodemailer');
const app = express();
// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));
/ Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.render('contact', { layout: false });
});
app.post('/send', (req, res) => {
console.log(res.body);
});
//Form HTML code
<form action="send" method="POST">
<input name="name" type="text" id="name" placeholder="NAME: First & Last">
<input name="email" type="text" id="email" placeholder="EMAIL:">
<textarea name="text" id="text" cols="30" rows="10" placeholder="QUESTION OR INQUIRY:"></textarea>
<br>
<button type="submit">Submit</button>
</form>
Have you tried console logging the req instead of the res for the app.post?
If you are doing console.log(req.body) then this should output a long json object. If this is not happening, then you are not hitting the url.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const nodemailer = require('nodemailer');
const app = express();
// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.render('contact', { layout: false });
});
app.post('/send', (req, res) => {
console.log(res.body);
});
The problem is in your html code. I have made some changes, Try this.
//Form HTML code
<form action="http://localhost:9000/send" method="POST">
<input name="name" type="text" id="name" placeholder="NAME: First & Last">
<input name="email" type="text" id="email" placeholder="EMAIL:">
<textarea name="text" id="text" cols="30" rows="10" placeholder="QUESTION OR INQUIRY:"></textarea>
<br>
<button type="submit">Submit</button>
</form>
I'm having trouble with my post from a registration form in node.js. Every time the form is posted the body the request has information but the body is empty. I'm new to node and express so it's probably something small but I can't for the life of me figure it out.
Here is my form in ejs:
<form class="form-signin" method="post" action="/users/register">
<div class="form-group">
<label class="sr-only" for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Enter Email" autocomplete="off">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
<div class="form-group">
<label class="sr-only" for="confirmPassword">Confirm Password</label>
<input type="password" class="form-control" id="confirmPassword" placeholder="Re-enter Password">
</div>
<button class="btn btn-dark mt-3" type="submit">Submit</button>
</form>
Here is my router code within the users router:
router.post('/register', function(request, response, next) {
console.log(request);
console.log(request.body)
response.render('register', { 'title': 'Register' });
});
Here is relevant output on the console:
console.log(request); output shortened this is just the tail.
_startAt: [ 299545, 483820242 ],
_startTime: 2018-09-20T16:08:59.366Z,
_remoteAddress: '::1',
body: {},
_body: true,
length: undefined,
read: [Function],
secret: undefined,
cookies: {},
signedCookies: {},
route:
Route {
path: '/register',
stack: [ [Object] ],
methods: { post: true } } }
{}
POST /users/register 200 21.906 ms - 2361
app.js code:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use(function(request, response, next) {
next(createError(404));
});
app.use(function(error, request, response, next) {
response.locals.message = error.message;
response.locals.error = request.app.get('env') === 'development' ? error : {};
response.status(error.status || 500);
response.render('error');
});
module.exports = app;
Things I've tried:
different browsers
different routes
writing simpler forms from scratch
formidable instead of body-parser
I'm pretty sure at this point that it's a problem with the ejs form because the body object in the request is always empty.
The <input> elements in the form must have a name attribute defined, not just id.
Another common error when using express, make sure you use body-parser
https://www.npmjs.com/package/body-parser
i.e
const router = express();
const bodyParser = require('body-parser');
router.use(bodyParser.json())
.use(bodyParser.urlencoded({
extended: true
}));
The other answer pointed out what you're missing and I updated your .ejs code to show you correct way of posting a html form:
<form class="form-signin" method="post" action="/users/register">
<div class="form-group">
<label class="sr-only" for="email">Email address</label>
<input type="email" name="email" class="form-control" id="email" placeholder="Enter Email" autocomplete="off">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" class="form-control" id="password" placeholder="Enter Password">
</div>
<div class="form-group">
<label class="sr-only" for="confirmPassword">Confirm Password</label>
<input type="password" name="confirmPassword" class="form-control" id="confirmPassword" placeholder="Re-enter Password">
</div>
<button class="btn btn-dark mt-3" type="submit">Submit</button>
</form>
You can either do the above or handle the submission with javascript/jquery if you're submitting a more complex form or need some sort of validation on fields.
See this answer: Submit a form using jQuery
I am using:
var express = require("express"),
app = express(),
bodyParser = require("body-parser");
with:
app.use(bodyParser.urlencoded({extended: true}));
Form:
<form action="/[route]" method="GET">
<input type="text" name="[name]">
<input type="submit" value="Show Results">
</form>
Route:
app.get("/[route]", function(req, res){
console.log(req.body.[name]);
});
The issue I am having is when I try to access the req.body.[name of input] it is 'undefined'
It's like the body parser is not working and I am not sure why.
I have followed a couple of different online attempts at this now and I keep getting undefined for my post data and console.log(JSON.stringify(req.body)) returns nothing also.. So I am going wrong somewhere...
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Chat</title>
</head>
<body>
<form action="/" method="post">
<button>Close</button><br/><br/>
<label for="username">Your Name: *</label><br/>
<input id="username" type="text" value="" name="username" autocomplete="off" required="required" /><br/>
<!-- <label for="email">Email: *</label><br/>
<input id="email" value="" name="email_address" autocomplete="off" required="required" /><br/> -->
<label for="phone">Phone:</label><br/>
<input id="phone" value="" name="phone" autocomplete="off" /><br/>
<label for="question">Question: </label><br/>
<textarea id="question" name="question">
</textarea required="required"><br/><br/>
<button type="submit">Chat</button>
</form>
</body>
</html>
JS:
var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/', function(req, res) {
var username = req.body.username;
res.send('<h1>Hello</h1> '+username);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Try to add Urlencoded option:
var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
// Add this line below
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/', function(req, res) {
var username = req.body.username;
res.send('<h1>Hello</h1> '+username);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Try to use express-fileupload package you can get data in req.body
var app = require('express')();
var http = require('http').Server(app);
const fileUpload = require('express-fileupload')
app.use(fileUpload());
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/', function(req, res) {
var username = req.body.username;
res.send('<h1>Hello</h1> '+username);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Problem Statement: When I am running node.js I am getting an error
Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/
Expected Result: The page should display and the user can insert data to the DB.
Here is my Code:
filter.js
var express = require('express'),
http = require('http'),
fs = require('fs'),
bodyParser = require('body-parser'),
io = require('socket.io'),
filter = express();
mongoose = require('mongoose');
//all environments
filter.set('port', process.env.PORT || 3000);
filter.set('views', __dirname + '/views');
filter.set('view engine', 'jade');
filter.use(express.bodyParser());
filter.use(express.methodOverride());
//filter.use(filter.router);
filter.use(express.static(path.join(__dirname,'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_emailid: String,
name: String,
age: Number
});
var user = mongoose.model('emp', Schema);
filter.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
})
});
filter.post('/new', function(res, req){
new user({
_emailid:req.body.email,
name:req.body.name,
age:req.body.age,
}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/view');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port' + app.get('port'));
});
Here is my HTML code:
<html>
<head>
<title>Please enter your details</title>
</head>
<body>
<h3>Please enter your details</h3>
<p>Please register below!!!</p>
<form action="/new" method="POST">
<label for="email">Email: </label>
<input type="email" name="email" /><br>
<label for="name">Name: </label>
<input type="text" name="name" /><br>
<label for="age">Age: </label>
<input type="number" name="age" /><t>
<input type="number" name="age" /><br>
<input type="submit" />
</form>
</body>
</html>
There are a number of changes with express 4.x. Like the error says, all of the middleware has been removed.
Update your package.json to include the "new" packages, a basic list can be found here and a full list, https://github.com/expressjs
Basically you need to edit
filter.use(express.bodyParser());
And replace it by,
filter.use(bodyParser());
You will have to do it for the methodOverride middleware as well.
Make sure you have all modules insatlled.
Hope this helps you,
var express = require('express'),
http = require('http'),
fs = require('fs'),
bodyParser = require('body-parser'),
methodOverride=require('method-override'),
io = require('socket.io'),
filter = express();
mongoose = require('mongoose');
//all environments
filter.set('port', process.env.PORT || 3000);
filter.set('views', __dirname + '/views');
filter.set('view engine', 'jade');
filter.use(bodyParser());
filter.use(methodOverride());
//filter.use(filter.router);
filter.use(express.static(path.join(__dirname,'public')));