req.body is undefined - nodejs - javascript

Here is my html:
<form action='/new' method='POST' >
<span>pool name: </span>
<input type="text" name="name" />
<input type="hidden" name="imageSrcList" />
<button type='submit' >Create new</button>
</form>
And here is the relevant JS:
var app = express()
app.use(fileUpload());
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/views'));
app.post('/new', (req, res) => {
console.log(req.body.name);
})
The console reads out:
TypeError: Cannot read property 'name' of undefined
I have tried with console.log(req.body) and this also is undefined.
Thanks in advance!

You're missing the body-parser middleware which is necessary to have req.body set to a value. Express doesn't come with this by default and will need to be installed via NPM npm i --save body-parser
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

Related

Cannot read property 'Image' of undefined error on Nodejs

I was Trying to make a shopping cart. i was making admin panel in which i need to submit the image for adding product. After creating the Form
<section>
<div class="container mt-4">
<div class="row">
<div class="col-md-6">
<h2 class="text-cnter">Add Product</h2>
<form action="/admin/add-product" method="POST" enctype="multipart/form-data">
<label for="">Name</label>
<input type="text" name="Name" class="form-control">
<label for="">Category</label>
<input type="text" name="Category" class="form-control">
<label for="">Price</label>
<input type="text" name="Price" class="form-control">
<label for="">Description</label>
<input type="text" name="Description" class="form-control">
<label for="">Image</label>
<input type="file" class="form-control">
<button class="btn btn-success mt-4" type="submit">Submit </button>
</form>
</div>
</div>
</div>
</div>
</section>
In admin.js file ( where router of admin )
router.get('/add-products',function(req,res){
res.render('admin/add-products')
});
// router.post('/add-product',function (req,res) {
// console.log('Got it')
// });
router.post( "/add-product", function( req, res ) {
console.log(req.body)
console.log(req.file.Image)
});
module.exports = router;
app.js file
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var hbs = require('express-handlebars');
var fileupload =require('express-fileupload');
var bodyParser = require('body-parser');
var userRouter = require('./routes/user');
var adminRouter = require('./routes/admin');
const {allowInsecurePrototypeAccess} = require('#handlebars/allow-prototype-access')
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
//Layout Directory Set
app.engine('hbs',hbs.engine({ extname:'hbs' , defaultLayout:'layout',layoutsDir:__dirname+'/views/layout/',partialsDir:__dirname+'/views/partials'}));
app.engine('handlebars', hbs.engine({
handlebars: allowInsecurePrototypeAccess(hbs)
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(fileupload());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', userRouter);
app.use('/admin', adminRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
after running with nodemon giving submit button shows
Cannot read property 'Image' of undefined
TypeError: Cannot read property 'Image' of undefined
Btw i was just started on nodejs .Thats why i dont know more about it.
You might want to check this line in your admin.js file:
console.log(req.file.Image)
Based on the error message req.fileis undefined and therefor it can't read Image.
The reason is, that express needs extra middleware to correctly handle multipart/form-data. Check out Multer. This should help you getting all the parts of your form including the file(s).
Also be aware that your file input does not have a same. So you definitely can't find it with Image.
Seems like req.file is undefined, so it can't read the property Image of undefined.
try changing this. first provide a name to your input file
<label for="">Image</label>
<input type="file" name = "img" class="form-control">
try getting the file then using
router.post( "/add-product", function( req, res ) {
console.log(req.body)
console.log(req.files.img)
});

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

Express.js req.body is undefined

edit:guys I'm genually new to all of this. here's the html form I used. should i update this question with something else?
<form action="/pesquisar" method="post">
<input type="text" id="cO">
<input type="text" id="cD">
<input type="submit">
</form>
I'm currently trying to design a simple browser app utilizing express. console.log(req.body) comes back {} and i cant find the solution, been here for the best part of the day lol
Here's my app
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res){
console.log(req.body);
res.render('index', {
infoVoos: 'acesso_inicial'
});
});
app.post('/pesquisar', function(req,res){
console.log("");
console.log("");
console.log(req.body);
res.send('ok');
});
app.listen(3000);
console.log('############');
console.log('Server on');
console.log('');
module.exports = app;
I changed the parameter of the input tag from "id" to "name" and it's working fine now.
original
<form action="/pesquisar" method="post">
<input type="text" id="cO">
<input type="text" id="cD">
<input type="submit">
</form>
new
<form action="/pesquisar" method="post">
<input type="text" name="cO">
<input type="text" name="cD">
<input type="submit">
</form>
thankx guys

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

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