1

I am trying to create an http server that reads only POST requests and returns the body of the request in upper case. This is my code:

http=require("http");
fs=require("fs");
http.createServer(function(req,res){
 if(req.method=="POST")
 {
 var body = '';
 req.on('data', function (data) {body += data.toString();});
 body=body.toUpperCase()
 res.end(body);
 }
 else
 {
 res.end("Not a POST request.");
 }
 }).listen(process.argv[2]);

When I run this from the command prompt (specifying a port number), I get the following error:

Error connecting to http://localhost:61777: read ECONNRESET

How do I get this work?

raul
  • 1,209
  • 7
  • 20
  • 36

1 Answers1

3

You have to send the body, after you finish to get it.

http.createServer(function(req,res){
 if(req.method=="POST")
 {
 var body = '';
 req.on('data', function (data) {body += data.toString();});

 // Please see this line:
 req.on('end', function (data) { body=body.toUpperCase();
 res.end(body);});

 }
 else
 {
 res.end("Not a POST request.");
 }
 }).listen(process.argv[2]);
Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117