Robert Sim
Robert Sim

Reputation: 1560

node.js POST callbacks not received

I am POSTing a json file to a node.js listener, and I must not fully understand how POSTs are properly constructed, because in the code below the on('data') callback is never invoked. I can see the actual json string in the body, so I can work around the lack of a callback, but it seems like I'm doing something wrong with how I generate my POST request. [Postman details further below]

// Server initialization
var server = restify.createServer();
server.use(restify.queryParser());
server.use(CookieParser.parse);
server.use(restify.bodyParser());

// Later, at the point where I register callbacks.
this.server.post('receive', function (request, respond) {
        console.log('Received POST');
        console.log("Headers: %s", JSON.stringify(request.headers));
        console.log("Body: %s", JSON.stringify(request.body));
        var body = '' ;
        var filePath = './data/notes.json';
        
        // this event is never triggered.
        request.on('data', function (data) {
            console.log('Data received.');
            body += data;
        });
        
        request.on('end', function () {
          console.log('End of POST');
          fs.writeFile(filePath, body, function () {
              respond.end();
          });                      
        });
    });

POST details: I'm using Postman to create a POST request, Content-Type: application/json and the putting the json string in the raw body. What will normally trigger the 'data' event in a POST request? If I ignore data events and just read from the request body, will I run into issues?

Payload details

Upvotes: 0

Views: 37

Answers (1)

robertklep
robertklep

Reputation: 203241

Since you're using restify.bodyParser, that middleware would have already read the request body so there isn't any more for your handler to read (hence no data events). A stream, like request, can only be read once, until it's exhausted. You can't "re-read" it.

Which also means that you can just use request.body, which should be the (parsed) result of the JSON that you're posting.

As an aside: I don't know Postman very well, but it looks like you're sending a JSON-encoded string to the server, as opposed to a JSON-encoded object.

To send the latter, I would expect that this should be the raw body data:

{"body":"this is a test"}

Upvotes: 2

Related Questions