from the client I'm doing :
$.ajax({
url: '/create',
type: 'POST',
data: JSON.stringify({
theme: "somevalue",
snippet: {
name: "somename",
content: "somevalue"
}
}),
complete: function (response)
{
}
});
on the server ( node.js/express.js
) I'm doing :
var app = express();
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
.......
...
app.post('/create', function (req, res)
{
var dataReceived = req.body;
});
I expected the value of dataReceived
to be :
{
"theme" : "somevalue",
"snippet" : {
"name": "somename",
"content" : "somevalue"
}
}
Instead the value of dataReceived
was :
{
'{"theme":"somevalue","snippet":"name":"somename","content":"somevalue"}}': ''
}
This is really weird and I can't find what I'm doing wrong. Any ideas?
from the BodyParser module documentation :
bodyParser.urlencoded(options)
Returns middleware that only parses urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).
Is this related to my problem ?
Express has a built-in express. json() function that returns an Express middleware function that parses JSON HTTP request bodies into JavaScript objects. The json() middleware adds a body property to the Express request req . To access the parsed request body, use req.
What Is Body-parser? Express body-parser is an npm module used to process data sent in an HTTP request body. It provides four express middleware for parsing JSON, Text, URL-encoded, and raw data sets over an HTTP request body.
In express, you will get req. body property. Basically, it is an object that will allow you to access data from the client-side in the form of a string or JSON Object.
Remove Stringify in your client side
$.ajax({
url: '/create',
type: 'POST',
data: {
theme: "somevalue",
snippet: {
name: "somename",
content: "somevalue"
}
},
complete: function (response)
{
}
});
or parse it again in server side
app.post('/create', function (req, res)
{
var dataReceived = JSON.parse(req.body);
});
Set this content-type on client side ajax call if you are going to use JSON.stringify
:
contentType: "application/json"
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