Node.js script is not running - node.js

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

Related

Contact form not submitting information to Terminal

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>

Value from FORM is not passed to Node JS

I have written a html form and trying to retrieve the values in node js server.
<form action="/newPost" method="post">
First Name: <br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
var express = require('express');
var bodyParser = require('body-parser');
const hbs = require('hbs');
var {ObjectID} = require('mongodb');
var {mongoose} = require('./db/mongoose');
var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var app = express();
hbs.registerPartials(__dirname + '/views/partials');
app.set('view engine', 'hbs');
app.use(bodyParser.json());
const port = process.env.PORT || 3000;
app.post('/newPost', (req, res) =>{
console.log(req.body.text);
console.log(req.params.firstname);
console.log(req.body.firstname);
res.send(req.body.firstname);
});
expecting mickey but shows undefined

Cannot post to a server in express

I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.
app.js:
var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();
app.engine('html', consolidate.nunjucks);
app.set('view engine', 'html');
app.set('views', './views');
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(3055);
module.exports = app;
routes/index.js:
const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();
router.get('/', function(req, res, next){
res.render('index.html');
});
router.post('/addsubject', function(req, res, next){
Patient.create(req.body).then(function(patient){
res.redirect('/profile');
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
} else {
return next(err);
}
}).catch(function(error){
res.send(500, error);
});
});
router.get('/profile', function(req, res, next){
res.render('./profile.html');
});
router.get('/addsubject', function(req, res, next){
// .... do something here ..
});
module.exports = router;
I have the <form action="/addsubject" method="post"> in my index.html file.
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>dabl Demographic</title>
<body>
<h2>Add Subject</h2>
<form action="/addsubject" method="post">
<label for="fname">First Name: </label>
<input type="text" name="fname" id="fname">
<br>
<label for="sname">Second Name: </label>
<input type="text" name="sname" id="sname">
<br>
<label for="dob">dob: </label>
<input type="text" name="dob" id="dob">
<br>
<label for="laterality">Laterality: </label>
<input type="text" name="laterality" id="laterality">
<br>
<button>Submit</button>
</form>
</body>
</html>
You pass wrong function (error handling function) to the POST route.
Just remove first "err" param from the function like this:
router.post('/addsubject', function(req, res, next){
Use body-parser middleware before app.router
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
...
Problem solved:
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
next(err); //next(err); called inide this block no more 404 error
}
User input is now succesfully passed through the body-parser.

req.body undefined using post method

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.

Posting form data with Nodejs and body-parser

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

Resources