I've been using Express.js and the body-parser module for parsing a form to the server. However, when the content is received, res.body it just shows up as an empty object.
app.js:
var express = require("express");
var app = express();
var bp = require("body-parser");
app.set('views', __dirname + '/views');
app.use(bp.json());
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.render('index.jade');
});
app.post('/', function (req, res) {
console.log(req.body);
});
app.listen(process.env.PORT || 5000);
The form (in Jade):
form(method="post", action="/", enctype="application/json")
input(type="text", name="name", placeholder="input your name")
Why is this so and how can it be fixed?
bodyparser.json() only parses requests with JSON data. You need to use bodyparser.urlencoded():
app.use(bodyParser.urlencoded({extended: false}))
extended: false means that nested values aren't handled, e.g. foo[bar]=baz. You can switch it to true if you want to support nested values.