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"}
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'})
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With