Is there a better way, in Node.js, to accept JSON data than appending chunked input to a string and running JSON.parse()
upon it afterward? The server can not assume that the JSON input is valid, and JSON.parse()
is the only way I'm aware of to validate JSON data.
Assume the following server accepts:
- only POST requests
- only JSON data
- only with a
Content-Type
header of"application/json"
.
var server = http.createServer(function(req, res) {
....
var parsedData;
var inputData = '';
req.on('data', function(chunk) {
inputData += chunk;
});
req.on('end', function() {
parsedData = JSON.parse(inputData);
}
....
}
If I am enforcing the input data so strictly, it seems strange to simply append this data to a string and then JSON.parse()
it, essentially (assuming proper JSON is inputted) going JSON -> string -> JSON
. (Of course, one can not assume the data is valid.)