I'm sending the following JSON string to my server.
(
{
id = 1;
name = foo;
},
{
id = 2;
name = bar;
}
)
On the server I have this.
app.post('/', function(request, response) {
console.log("Got response: " + response.statusCode);
response.on('data', function(chunk) {
queryResponse+=chunk;
console.log('data');
});
response.on('end', function(){
console.log('end');
});
});
When I send the string, it shows that I got a 200 response, but those other two methods never run. Why is that?
Sometimes you don't need third party libraries to parse JSON from text. Sometimes all you need it the following JS command, try it first:
For Express v4+
install body-parser from the npm.
https://www.npmjs.org/package/body-parser#installation
I think you're conflating the use of the
response
object with that of therequest
.The
response
object is for sending the HTTP response back to the calling client, whereas you are wanting to access the body of therequest
. See this answer which provides some guidance.If you are using valid JSON and are POSTing it with
Content-Type: application/json
, then you can use thebodyParser
middleware to parse the request body and place the result inrequest.body
of your route.Test along the lines of:
Updated for Express 4+
Body parser was split out into it's own npm package after v4, requires a separate install
npm install body-parser
Update for Express 4.16+
Starting with release 4.16.0, a new
express.json()
middleware is available.