Express and Body-Parser not returning values - javascript

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

Related

Cannot read property 'task' of undefined

enter image description hereI never faced this problem before but now "req.body.task" is not working and I don't know why its happening.
Here's the form
<form action="/" method="POST">
<div class="input-box">
<input type="text" name="task" id="" class="input-add">
<button type="submit" name="button" class="btn-add">+</button>
</div>
</form>
Here's the post request
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.set(bodyParser.urlencoded({extended: false}));
app.use(express.static("public"));
let items = [];
app.get("/", (req,res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/", (req,res) => {
const item = req.body.task;
console.log(item);
});
app.listen(3000, () => {
console.log("Server running at port 3000");
});
This
app.set(bodyParser.urlencoded({extended: false}));
should be
app.use(bodyParser.urlencoded({extended: false}));
BodyParser is a middleware and should be used using app.use methods.
See the docs for more details
app.set is used to set values to app variables, for example view engines

How do I read the data sent to my express route?

I don't know why, but when I try to view my data using req.body.newFullName I get an empty object. The post is going to the correct route but I don't know how to access the form's field data that was sent by the XMLHttpRequest.
Below is most of the code I used.
route setup app.js
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.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
route details users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
/* POST contacts */
router.post("/", function(req,res,next){
data = req.body.newFullName;
res.send(data);
})
module.exports = router;
form details index.html
...
<form id="contacts">
<label for="FullName">Full Name:</label>
<input type="text" name="newFullName" placeholder="Enter Full Name..."><br>
<input type="submit" value="Submit data">
</form>
...
js that submits form data
window.addEventListener("load",function(){
function createContact(){
var XHR = new XMLHttpRequest();
var frmData = new FormData(form);
XHR.open("POST", "http://localhost:3000/users/");
XHR.send(frmData);
};
var form = document.getElementById("contacts");
form.addEventListener("submit", function(event){
event.preventDefault();
createContact();
});
});
Thanks for your help in advance!
The problem is the client-side code; you're sending multipart/formdata but expecting application/x-www-form-urlencoded on the server.
Here's the current way to send that:
function createContact() {
const payload = new URLSearchParams(new FormData(form));
fetch("http://localhost:3000/users/", {
method: "POST",
body: payload
})
.then(rawReply => rawReply.text())
.then(reply => console.log("reply", reply))
.catch(err => console.error(err));
};
If you check the request in the browser, you'll find it now properly shows the params instead of raw text.

Nodejs post method - req.body.variable undefined

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

Cannot get info from post method in express

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

No found page (express 4 + body-parser + form + post)

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

Categories

Resources