【发布时间】:2011-06-28 05:26:32
【问题描述】:
我正在尝试构建一个带有控制台日志记录的 Node.js 服务器,类似于 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 错误。
【问题讨论】:
标签: javascript node.js