7
votes

This is my Node Express Code,

(function () {
    'use strict';
    var fs = require('fs');
    var cors = require('cors');
    var bodyParser = require('body-parser');
    var express = require('express'),
        app = express(),
        port = 8112;


    app.use(cors());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.listen(port);


    app.route('/abc')
        .post(abc);


    function abc(req,res){
        console.dir(req.body);
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.sendStatus(200);
    }

})();

But Im getting request body as

{}

But in my network Tab in Chrome I can see request payload. Please note OPTIONS is fired before this POST call.

Request headers

POST /abcHTTP/1.1 Host: localhost:8112 Connection:
keep-alive Content-Length: 11 Pragma: no-cache Cache-Control: no-cache
Origin: http://localhost:4200 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
x-api-key:CExkxDlFC35ckfCGX6m61x76GxIYH2h2Iv8bX874
Content-Type:text/plain;charset=UTF-8
Accept: / Referer: http://localhost:4200/dashboard Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

Request Payload

{"dd":"dd"}

5
Can you show your request? including headers, please. (Update your question wit it)Marcos Casagrande
res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); are pointless as you are using the cors middleware.Quentin
Content-Type: text/plain should probably be Content-Type: application/jsonRoland Starke

5 Answers

14
votes

You need to send: Content-Type: application/json for bodyParser.json() to work, without it, your JSON payload won't be parsed, that's why you get: {}

From the docs:

The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option, or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.

Example using .fetch:

fetch('http://localhost:4200/dashboard', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({dd: 'dd'})
});
4
votes

Your content-type header is text/plain. Please try replacing

app.use(bodyParser.json());

with

app.use(bodyParser.text());
0
votes

Hi @Pradhaban Nandhakumar, I think you have to pass data as row data. Try below code snippets.

You should always pass raw data .

app.post('/users', (req, res) => { res.send(req.body); });

0
votes

You are posting a plain-text string instead of a JSON. Consider showing us how you are posting data (jQuery, Fetch API, etc).

Just have to specify

headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json'
}

in your request headers (front-end). The Express body parser should then be able to detect the valid JSON and print the result. Note that Accept isn't required but it instructs the server that the client understands and accepts a JSON response.

Alternatively, use a simple library like Easy Fetch on the front-end to manage server-side calls without having to deal with response parsing or header settings.

0
votes

This normally happens because of the "Content-type" header in your http request.

JSON Bodies
bodyParser.json() only accepts the type of "application/json" and rejects other non-matching content types.

Solutions 1: Accepting Extra Content Types Other Than application/json

check your request header "Content-type" and add it to options argument in bodyParser.json([options]) in server.

for example if you have this:
"Content-type: application/csp-report"

app.use(bodyParser.json({ type: ["application/json", "application/csp-report"] }));

you can also use the built-in middleware in exprss v4.16.0 onwards:

app.use(express.json({ type: ['application/json', 'application/csp-report'] }));

for more information see this documentation

Notice: use this approach only where you can not change Content-type to application/json.

Solutions 2 ( recommended ): Change Header content-type To application/json In Http Request.

What about urlencoded bodies ?
This is similar to json bodies with two differences:

  1. "Content-type" header accepted in request is "application/x-www-form-urlencoded"

  2. body payload is a url encoded format (Not a json object):
    Format: param_1=value_1&param_2=value_2&...

app.use(express.urlencoded({ extended: false }));

see docs.