Reputation: 101
I have a POST request (content-type: text/plain) with this body: {"initObj":{"UDID":"123456"}}
It shows "Cannot read property 'UDID' of undefined"
When I do this:
console.log(req.body);
It shows the request body correctly, but when I do this:
console.log(req.body.initObj);
it shows undefined
Here is the configuration of the server:
app.use(cors());
app.use(bodyParser.text());
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true })); //true
// override with the X-HTTP-Method-Override header in req
app.use(methodOverride('X-HTTP-Method-Override'));
Upvotes: 0
Views: 77
Reputation: 203231
If you upload the data as text/plain
, req.body
will be a string (containing some JSON text, but because it's uploaded as text, body-parser
won't parse it into a proper object). And strings don't have a property called initObj
.
You should either parse the data yourself:
let data = JSON.parse(req.body);
console.log(data.initObj);
Or upload as application/json
(which makes more sense to me).
Upvotes: 1