user3554072 user3554072 - 4 months ago 30
Node.js Question

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

{}

Answer

Try

app.use(bodyParser.urlencoded())
Comments