简体   繁体   中英

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

Change it to:

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

And then:

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

And now you can access response. ;)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM