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);
Related
So I'm developing a chat server using expressjs and socketio and decided to create an admin where backend built in with the node chat server itself.
const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));
let socketList = io.sockets.server.eio.clients;
const path = require('path');
const bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/login', function(req, res) {
res.render('login', { title: 'Login | Argos Chat' });
});
app.post('/login', function(req, res) {
console.log(req.body);
});
So upon login data submission, I tried to display the post data from the login form but it returns me an empty object {}
console.log(req.body);
Tried to do req.params but same result .Any help, ideas is greatly appreciated.
I tried running your code and its working fine. Maybe the way you are calling the API is not right
To support content-type: x-www-form-urlencoded you should use
app.use(bodyParser.urlencoded({ extended: true }));
and to support content-type: application/json you should use
app.use(bodyParser.json());
I think you are using form-data, for that neither of these will work. For that you may want to use formidable package. We should use form-data content type only when we are sending any images/file.
And body-parser has been merged with express. You can directly use this now
app.use(
express.json(),
express.urlencoded({ extended: false })
);
I think this might be a right solution for your problem, as everything seems to be right in your code, the error might be caused by the way you are calling the API and you are setting the headers:
https://stackoverflow.com/a/25904070/12090205
const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));
let socketList = io.sockets.server.eio.clients;
const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/login', function(req, res) {
res.render('login', { title: 'Login | Argos Chat' });
});
app.post('/login', function(req, res) {
console.log(req.body);
});
I checked Its Working.
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 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 }));
I am trying to get data from a form using express js.But i will get an undefined error in my console.
here is my html
<form action="/login" method="post">
<label>Username</label>
<input type="text" name="username" value=""><br><br>
<label>Password</label>
<input type="password" name="password" value=""><br><br>
<input type="submit" name="" value="Login">
</form>
index.js
var app = require('express')();
var url = require('url');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var mongoose=require('mongoose');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// for login
app.post('/login',function(req,res){
console.log("server"+req.body.username+req.body.password);
});
I will get undefined error in my console,also i have installed body-parser in my application.
I'm not having issue with this code:
var app = require('express')();
var server = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/login',function(req,res){
console.log(req.body);
console.log("server"+req.body.username+req.body.password);
});
var server = app.listen(3000);
And testing with:
curl 'http://127.0.0.1:3000/login' --data 'username=zetg&password=zetgze'
I don't know what is wrong with your code, but try going slowly step by step, and including your functionalities one by one.
I've been using Express.js and the body-parser module for parsing a form to the server. However, when the content is received, res.body it just shows up as an empty object.
app.js:
var express = require("express");
var app = express();
var bp = require("body-parser");
app.set('views', __dirname + '/views');
app.use(bp.json());
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.render('index.jade');
});
app.post('/', function (req, res) {
console.log(req.body);
});
app.listen(process.env.PORT || 5000);
The form (in Jade):
form(method="post", action="/", enctype="application/json")
input(type="text", name="name", placeholder="input your name")
Why is this so and how can it be fixed?
bodyparser.json() only parses requests with JSON data. You need to use bodyparser.urlencoded():
app.use(bodyParser.urlencoded({extended: false}))
extended: false means that nested values aren't handled, e.g. foo[bar]=baz. You can switch it to true if you want to support nested values.