I have made super simple code for the sole purpose of receiving data from the client.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var PORT = 80;
app.get('/',function(req,res){
res.send('<form action="/" method="post"> <input type="text"name="firstname" value="Mickey"><input type="submit" value="Submit"> </form>');
});
app.post('/', function (req, res) {
console.log(req.body.firstname);
res.send('POST request to the homepage');
});
app.listen(PORT, () => console.log("Listening on port "+PORT));
That is it. but when I run it it says that req.body.firstname is undefined.
What am I doing wrong?
To parse form data, you'll have to use the bodyParser.urlencoded middleware.
Add the following to your code, before you handle the POST request:
app.use(bodyParser.urlencoded({ extended: false }));
Related
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
I am new to nodejs and express in general. I am trying to get a POST value from a html page using body-parser. I tried following several suggestions in SO but unable to make it work for me.
Here is the code. Any pointers will be highly appreciated. Thanks in advance.
Server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var Subscribe = require('./models/subscribe');
mongoose.connect('CREDENTIALS');
var app = express();
app.use(bodyParser.json(), bodyParser.urlencoded({ extended: false }));
var port = 3000;
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'Test...' });
});
var subscribeRoute = router.route('/subscribe');
subscribeRoute.post(function(req, res) {
var subscribe = new Subscribe();
subscribe.email = req.body.email_notify;
console.log(subscribe);
subscribe.save(function(err) {
if (err)
res.status(500).send(err);
res.status(200);
});
});
app.use('/api', router);
app.listen(port);
index.html
<form action="http://localhost:3000/api/subscribe/" method="POST" enctype="application/json">
<input type="text" onfocus="if (this.value=='E-mail Address') this.value = ''" onblur="if (this.value=='') this.value = 'E-mail Address'" value="E-mail Address" id="email_notify" name="email_notify" />
<button id="notify_me" ontouchstart="">Notify Me!</button><br/>
</form>
Thanks
Sujith
change this
app.use(bodyParser.json(), bodyParser.urlencoded({ extended: false }));
To this
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Make <input type='submit'> instead of the <button> and remove enctype form the form.
Also in Chrome open developer tools, network tab and check that the request is sent to your server at all
I need to create a Node server only for receiving POST requests. With the information in the body of the request, I need to create a system call. How do I do so? So far, I only have:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser);
app.post('/', function(req, res){
console.log('POST /');
console.dir(req.body);
});
port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port)
However, when I make a POST request to 127.0.0.1:3000, the body is undefined.
var request = require('request');
request.post(
'127.0.0.1:3000',
{ form: { "user": "asdf" } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
You've got a middleware problem here. The express.bodyparser() middleware is deprecated in Express 4.x. This means you should be using the standalone bodyparser middleware.
Oddly enough, you're importing the correct middleware by doing:
var bodyParser = require('body-parser');
However, you should be using it differently. Take a look at the docs and the example given:
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
In the newest version of express, express.bodyParser is not used. See the reference
I want to receive data from client, so I use express 4 and middleware body-parser.
But I input url:localhost:5555/book, page show the message: Name: undefined,
and I input url:localhost:5555/book/form.html, page show the message Cannot POST /book/form.html.
Here is my code.
form.html
<form action='./book' method='post'>
<input type='text' name='name' value='fred'>
<input type='text' name='tel' value='0926xxx572'>
<input type='submit' value='Submit'>
</form>
server.js
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post('/book', function(req,res){
console.log(req.body.name);
console.log(req.body.tel);
res.send('Name: '+req.body.name);
res.send('country: '+req.body.tel);
res.end();
});
app.listen(5555);
From what I see, you're doing a app.post on the route /book so express expects a POST request.
But when you go to the url http://localhost:5555/book you are doing a GET request, thus the error.
There should be one page (a GET request therefore a app.get) for displaying the form and one page for accepting post requests.
I don't use html ,I replaced by jade.
And I use app.route().
form.jade
form(action='./book' method='post')
input(type='text' name='name' value='fred')
input(type='text' name='tel' value='0926xxx572')
input(type='submit' value='Submit')
server.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.set('views', './views');
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.route('/book')
.get(function(req, res) {
//res.send('Get a random book');
res.render('form');
})
.post(function(req, res) {
res.send('Name: '+req.body.name +'<br>'+ 'tel: '+req.body.tel);
})
app.listen(5555);
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);