Im using body parser with express but is not working and it is returning empty object when i print req.body in the console.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine','ejs');
app.get('/' ,function(req,res){
var name = "ganesh"
console.log(req.body.name);
res.render('home',{name : name});
});
app.post('/postname' , function(req,res){
res.redirect("/");
});
app.listen(3000,function(){
console.log("server started");
};
this is my home.ejs file
<html>
<head>
<title>practice</title>
</head>
<body>
<h1>
hello<%= name %> This is the home page
</h1>
<form action="/postname" method = "POST">
<input type = "text" name="name">
<button>
go
</button>
</form>
</body>
i have correctly installed body-parser ejs and express
this is printed in the console:
server started {}
You are redirecting the postname
request to /
, Please note that this will not forward request data
to /
root route.
The res.redirect("/")
will send a response back to client with 302
status, and then the client will make a Get
request to /
route without any data. hence the request.body
will always has empty data in Get
request.
You could handle the data in postname
route and then redirect it.
If you want to forward the data from postname
to /
route then you could pass it in the query string
.
Example:
var app = express();
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
var name = "ganesh"
res.render('home', { name: req.query.name });
});
app.post('/postname', function (req, res) {
var name = "ganesh"
console.log(req.body.name);
// handle the post data here
res.redirect("/?name=" + req.body.name);
});
app.listen(3000, function () {
console.log("server started");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.