why unable to display value of title? - node.js

I am trying to output the value of title which i entered in the form in the /Add-Product link
Here is my app.js code
const http= require('http');
const path= require('path');
const express= require('express');
const app= express();
app.set('view engine', 'ejs');
app.set('views', 'Views');
app.use(express.static(path.join(__dirname, 'Public')));
app.get('/', (req, res, next)=>{
res.render('shop');
});
app.get('/admin', (req, res, next)=>{
res.render('admin');
});
app.get('/add-product', (req, res, next)=>{
res.render('addProduct');
});
app.post('/add-product', (req, res, next)=>{
console.log(req.body.title); //uable to display value of req.body.title
res.redirect('/');
});
app.listen(3000);
form part of the addProduct.ejs
<main>
<form action="/add-product" method="POST">
<p>Title</p>
<input type="text" name="title" id="title"/>
<p>Price</p>
<input type="text" name="price"/>
<p>Description</p>
<input type="text" name="description"/>
<button type="submit">Submit</button>
</form>
</main>
Unable to figure why the req.body.title is throwing an error as:Cannot read property 'title' of undefined
Please guide me on what i am missing.

By default, form submits the data to server in the content type of application/x-www-form-urlencoded. So you need to configure node js to receive this type of content. Use bodyParser to read the request body with json and encoded content.
Usage:
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));

Related

What is the reason req.body is displayed as undefined?

Hi i am making a blog with node js. And now I am implementing the function to write a post, but there is a problem in this process.
new.ejs is a screen for creating a post.
new.ejs
<div>
<h2> new post </h2>
<form action="/articles" method = "POST">
<h4>title</h4>
<input required type="text" name = "title" / class='form-control'><br>
<h4>description</h4>
<textarea name="description" class = 'form-control'></textarea><br>
<h4>contents</h4>
<textarea id="mytextarea" name="contents" rows = '10'></textarea>
취소<button type = "submit" class="btn btn-primary">저장</button>
</form>
</div>
and
article.js
var express = require("express");
var app = express();
var router = express.Router();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
router.get("/", function (req, res) {
res.send("article");
});
router.get("/new/home", function (req, res) {
res.render("articles/index");
});
router.get("/new", function (req, res) {
res.render("articles/new");
});
router.post("/", function (req, res) {
console.log(req.body.title);
});
module.exports = router;
Here, when req.body.title is executed, req.body becomes undefined. And in the code editor window, a sentence stating that bordyParser has been deprecated appears as the middle line is drawn. How to solve it
The EJS file is POSTing to /articles, but your POST route in the NodeJS is /.
To fix the 'body-parser is deprecated' messages, change the code as follows :-
...
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
...
to
...
app.use(express.urlencoded());
...
Body Parser is now part of Express itself.

How can I receive post data in a node js server with express?

I tried two middlewares but still getting this output in the terminal:
{}
my node js server code:
express = require('express');
bodyParser = require('body-parser');
const app = express();
//the middlewares i tried
app.use(express.urlencoded({extended: false}));
app.use(bodyParser());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/client.html');
});
app.post('/test', (req, res) => {
res.send('this is a test path');
console.log(req.body);
});
app.listen(3000, () => {
console.log('server listening...');
});
my form (client.html file):
<form method="POST" action="/test">
<input type="text">
<input type="submit">
</form>
I also tried send the post data with postman. I know that the action in the html form is working because I can see the "this is a test path" output in the browser
try this
express = require('express');
bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/client.html');
});
app.post('/test', (req, res) => {
res.send('this is a test path');
console.log(req.body);
});
app.listen(3000, () => {
console.log('server listening...');
});
also in html form , add name property in input tag
<form method="POST" action="/test">
<input type="text" name="email">
<input type="submit">
</form>
in fact it works just like
app.use(express.urlencoded());
the wrong thing was the nameless input in the html form
you should write code like this
var app=express();
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
app.post('/test', (req, res) => {
console.log(req.body.email);
res.send('this is a test path'+req.body.email);
});

Cannot post to a server in express

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.

req.body returns empty object when posting using form data in nodejs express

I'm doing a post request to '/' with a simple text input and expecting to see the data entered in req.body.course. When console logging req.body.course, I am getting an empty object back.
HTML
<html>
<head><title>New Course</title></head>
<body>
<form id="myform" action="/" method="post">
<input type="text" name="course" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
</body>
</html>
SERVER
var express = require('express');
var bodyParser = require('body-parser');
var app = express()
app.use(bodyParser.json())
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.post('/', function (req, res) {
var course = req.body.course;
res.send(course);
});
app.get('/', function (req, res) {
res.render('index');
});
app.listen(4000, function() {
console.log("Server is listening on port", 4000);
});
OUTPUT OF REQ.BODY
{}
Try
app.use(bodyParser.urlencoded())
you have to tell in headers what is the MIME type of your request
just add in request.
Content-Type='application/json'
Try to add the urlencoded middleware.
app.use(bodyParser.urlencoded())
or
app.use(bodyParser.urlencoded({
extended: true
}))
This parses URL encoded bodies since your request format is urlencoded.
You can refer to bodyparser urlencoded documentation.

Unable to post form details using Express js

My express code:
var express = require('express');
var bodyParser= require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('default', {title: 'Home', users: ['a', 'b', 'c']});
});
app.post('/me', function(req, res){
res.send("2nd page");
var t1= req.body.username;
console.log(t1);
});
My template:
<form method="post" enctype="multipart/form-data" action="/me">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
I'm trying to print the form values in submitted page
I have not added any jQuery or anything in the head section
What's the mistake?
Problem is with your form enctype, I am using jade template system, just add "jade": "^1.6.0" in your package.json and do npm install
Server Code
var express = require('express');
var app = express();
var bodyParser= require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('test');
});
app.post('/me', function(req, res){
console.log(req.body.username);
res.send("done");
});
app.listen(8081);
console.log("Listening at 8081");
views/test.jade
doctype html
html
form(method="post",enctype="application/x-www-form-urlencoded" action="/me")
input(type="text",name="username")
input(type="password" name="password")
input(type="submit")
if you want multipart/form-data you need to use
var multer = require('multer'); app.use(multer())

Resources