I have this as configuration of my Express server
app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: \"keyboard cat\" }
Credit to @spikeyang for the great answer (provided below). After reading the suggested article attached to the post, I decided to share my solution.
When to use?
The solution required you to use the express router in order to enjoy it.. so: If you have you tried to use the accepted answer with no luck, just use copy-and-paste this function:
function bodyParse(req, ready, fail)
{
var length = req.header('Content-Length');
if (!req.readable) return fail('failed to read request');
if (!length) return fail('request must include a valid `Content-Length` header');
if (length > 1000) return fail('this request is too big'); // you can replace 1000 with any other value as desired
var body = ''; // for large payloads - please use an array buffer (see note below)
req.on('data', function (data)
{
body += data;
});
req.on('end', function ()
{
ready(body);
});
}
and call it like:
bodyParse(req, function success(body)
{
}, function error(message)
{
});
NOTE: For large payloads - please use an array buffer (more @ MDN)
The Content-Type in request header is really important, especially when you post the data from curl or any other tools.
Make sure you're using some thing like application/x-www-form-urlencoded, application/json or others, it depends on your post data. Leave this field empty will confuse Express.
Most of the time req.body is undefined due to missing JSON parser
const express = require('express');
app.use(express.json());
could be missing for the body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
and sometimes it's undefined due to cros origin so add them
const cors = require('cors');
app.use(cors())
var bodyParser = require('body-parser');
app.use(bodyParser.json());
This saved my day.
As already posted under one comment, I solved it using
app.use(require('connect').bodyParser());
instead of
app.use(express.bodyParser());
I still don't know why the simple express.bodyParser()
is not working...
in Express 4, it's really simple
const app = express()
const p = process.env.PORT || 8082
app.use(express.json())