我試圖用類似於Django的開發服務器的控制檯日誌記錄來構建一個Node.js服務器。例如。Node.js - 記錄響應statusCode到控制檯(一個Django開發服務器)
[27/Jun/2011 15:26:50] "GET /?test=5 HTTP/1.1" 200 545
以下server.js(基於Node Beginner Book tutorial)得到我的時間和請求信息:
var http = require("http");
var url = require ("url");
var port = 1234;
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
var query = url.parse(request.url).query;
route(handle, pathname, query, response);
logRequest(request);
}
http.createServer(onRequest).listen(port);
console.log("\nServer running at http://192.168.1.5:" + port + "/");
console.log("Press CONTROL-C to quit.\n");
}
function logRequest(request) {
var pathname = url.parse(request.url).pathname;
var query = url.parse(request.url).query;
if (query == undefined) {
query = "";
}
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var hours = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
console.log("[" + year + "/" + month + "/" + day +
" " + hours + ":" + minutes + ":" + seconds + '] "' +
request.method + " " + pathname + query +
" HTTP/" + request.httpVersion + '"');
}
exports.start = start;
問:我怎麼會更新這個代碼來獲取response.statusCode和任何的「545」號碼是否進入日誌輸出?
當我嘗試將響應對象添加到logRequest函數時,響應statusCode始終爲「200」,即使我知道(通過調試日誌記錄)我的router.js正在生成404錯誤。