user4062487
user4062487

Reputation:

Node.js http server, function can't access response object

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

Upvotes: 0

Views: 639

Answers (2)

KennyXu
KennyXu

Reputation: 139

Try this:

var server = http.createServer(function (req, response) {
  var body = "";
  req.on("data", function (data) {
    body += data;
  });
  var parseRequest = function (data) {
    try {
       var jsonData = JSON.parse(data);
       handleRequest(jsonData);
    } catch (e) {
      console.log("Json Parse Failed")
      console.log(e);
      response.writeHead(500);
      response.end("Json Parse Failed");
    }
  };
  req.on("end", function (){
    parseRequest(body);
  });
}).listen(8080);

Upvotes: 0

Sebastian Nette
Sebastian Nette

Reputation: 7832

Change it to:

req.on("end", function (){
    parseRequest(response, body);
});

And then:

var parseRequest = function (response, data) { ...

And now you can access response. ;)

Upvotes: 1

Related Questions