Limiting the length of POST data to prevent filling memory?
A POST from a client sends a header and a block of data. If a client sends too much data at once the server will run out of space and crash. I added code to ignore POST data over a certain size.
Is this sufficient or should an req.on('data) be used to drain the buffer at the req source?
function serveHTML(){
var http=require("http").createServer(onPageRequest).listen(8080);
}//end serveFile
var pdata="";
function onPageRequest(req, res) {
//console.log("Req= ",req);
//console.log("Header",req.headers);
if (req.method=="POST") {
console.log("Post");
doPost(req,res);
}else{
doGet(req,res);
}//endif
}//end on PageRequest
var pobj;
function doPost(req,res){
var length;
length=req.headers["Content-Length"];
//do we want to take the message based on length?
if(length<1024){
req.on("data", function(d) {pdata+=d;if(pdata.length==length)doPost1(req,res);});
}else{
/*********
Should an req.on('data') be used here to drain the source and toss the data?
*/
res.writeHead(413); //Too big error
res.end(); }//end if length
req.on('close',"console.log(\"Closed\",pdata);");
}
The POST message processing code follows.
function doPost1(req,res){
var length;
var a = url.parse(req.url, true);
console.log("URL ",a);
console.log("XXX ",a.pathname);
length=req.headers["Content-Length"];
console.log("Length ",length);
console.log("pdata= ",pdata);
console.log("pdata length= ",pdata.length);
switch (a.pathname){
case "/CMD": //Process JSON command structure
if(pdata.length==length){
pobj=JSON.parse(pdata);
console.log(pobj);
if(pobj.cmd !==null){
eval(pobj.cmd);
pdata=JSON.stringify(pobj);
res.writeHead(200);
res.end(pdata);
}else{
res.writeHead(201);
res.end();
} //end if pobj.cmd
}//endif length else
break;
case "/LOGdata": // Process data POSTed into a form, simple Echo for now
console.log("LOGdata= ",pdata);
res.writeHead(200);
res.end(pdata);
break;
default:
res.writeHead(404);
res.end();
}//end switch
pdata="";
}//end doPost1
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
Limiting the length of POST data to prevent filling memory?
A POST from a client sends a header and a block of data. If a client sends too much data at once the server will run out of space and crash. I added code to ignore POST data over a certain size.
Is this sufficient or should an req.on('data) be used to drain the buffer at the req source?
The POST message processing code follows.