I have the following http server code
var server = http.createServer(function (req, response) {
body = "";
req.on("data", function (data) {
body += data;
});
req.on("end", function (){
parseRequest(body);
});
}).listen(8080);
var parseRequest = function (data) {
try {
jsonData = JSON.parse(data);
handleRequest(jsonData);
}
catch (e) {
console.log("Json Parse Failed")
console.log(e);
response.writeHead(500);
response.end("Json Parse Failed");
}
}
I thought that the parseRequest function should be able to access it's variables in in its parent function's scope. Is there something I am doing wrong here?
The error I get is,
response.writeHead(500);
^
ReferenceError: response is not defined
parseRequestinside the same scope as response if you want it to use response.createServercallback is not the parent scope ofparseRequest. Move it inside there and it would work.variable declarations forbodyandjsonData. Please use strict mode to avoid such accidental globals.