Express.js : POST data as KEY of a req.body object instead of VALUE of req.body?
Solution 1
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);
});
Solution 2
Set this content-type on client side ajax call if you are going to use JSON.stringify
:
contentType: "application/json"
Solution 3
just remove this content type from client request header
'Content-Type':'application/x-www-form-urlencoded'
Related videos on Youtube
Kawd
Updated on June 22, 2022Comments
-
Kawd almost 2 years
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 ?
-
Safari over 8 yearsyou dont need to JSON.stringify the request on the frontend.
-
-
Kawd over 8 yearsYou were right!. I still don't know when my data should be stringified and when it shouldn't be.. anyway.. thanks!
-
Samundra Khatri over 8 yearsi think if you are doing javascript on both client and server then no need of stringify !