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');
});
Related
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.
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.
var multer = require('multer');
var mwMulter1 = multer({ dest: './uploads1/' });
app.post('/files1', mwMulter1, function(req, res) {
// check req.files for your files
});
var mwMulter2 = multer({ dest: './uploads2/' });
app.post('/files2', mwMulter2, function(req, res) {
// check req.files for your files
});
app.post('/test', function(req, res){
var name = req.body.name;
console.log("Name is --- "+name);
res.json("name sent to server");
});
Whenever using multiple instances of multer then post data is not getting it is displayed undefined format.
You need use multer middleware. Try this:
app.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser());
app.get('/', function (req, res) {
require('fs').readFile('index.html', function(error,d) {
res.send(d.toString());
});
});
var multer = require('multer');
var mwMulter1 = multer({ dest: './uploads1/' }).single("name");
app.post('/files1', mwMulter1,function( req,res){
console.log(req.file);
res.end();
});
var mwMulter2 = multer({ dest: './uploads2/' }).array("name[]",2);
app.post('/files2', mwMulter2, function(req, res) {
console.log(req.files);
res.end();
});
app.post('/test', function(req, res){
var name = req.body.name;
console.log("Name is --- "+name);
res.json("name sent to server");
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
index.html:
Action: test
<form name="fileupload" action="test" method="POST" enctype="multipart/form-data">
<input name="name" type="file"/>
<button>submit</button>
</form>
<hr/>
Action: files1
<form name="fileupload2" action="files1" method="POST" enctype="multipart/form-data">
<input name="name" type="file"/>
<button>submit</button>
</form>
<hr/>
Actions: files2
<form name="fileupload3" action="files2" method="POST" enctype="multipart/form-data">
<input name="name[]" type="file"/><br/>
<input name="name[]" type="file"/>
<button>submit</button>
</form>
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')));
This is my server.js file:
var express = require("express");
var bodyParser = require("body-parser");
var controllers = require('./controllers');
var app = express();
controllers.init(app);
app.set('view engine', 'vash');
app.use(bodyParser());
app.use(express.static(__dirname + "/public"));
app.listen(5000);
This is my index.js code in controllers folder:
(function(controllers){
var homeController = require('./homeController');
controllers.init = function(app){
homeController.init(app);
};
})(module.exports);
This is my homeController.js code:
(function(homeController){
homeController.init = function(app){
app.get('/', function(req, res){
res.render('index', {title: "The Board"});
});
app.post("/", function(req, res){
console.log(req.headers);
console.log(req.body);
});
};
})(module.exports);
And this is my HTML:
#html.extend('layout', function(model){
#html.block('body', function(model){
#if(model.error){
<p class="text-error">Error occurred: #model.error</p>
}
<div class="row">
<form action="/" method="post">Enter your name:
<input type="text" name="userName" placeholder="..." />
<br>
<button type="submit">Submit</button>
</form>
</div>
})
})
When I make the post action req.body is undefined. How can I solve this problem?
Move app.use(bodyParser()); before route declaration controllers.init(app);