簡體   English   中英

Node.js http服務器,函數無法訪問響應對象

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

我有以下HTTP服務器代碼

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

我認為parseRequest函數應該能夠在其父函數范圍內訪問其變量。 我在這里做錯什么了嗎?

我得到的錯誤是,

response.writeHead(500);
^
ReferenceError: response is not defined

更改為:

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

接着:

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

現在您可以訪問響應。 ;)

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM