我有一个 node.js 应用程序,当我尝试加载主页时遇到错误消息。我会尽力在下面布置我的架构。它是 index.js --> server.js --> router.js --> requestHandlers.js
我正在使用 express (www.expressjs.com) 和 nodebeginner.org 的组合。很抱歉这个长问题..只是想尽可能多地获取信息。
index.js(创建包含路径名/请求处理程序信息的句柄对象,调用函数来启动服务器)我在这里从 router.route 开始,并在每个步骤中传递它
var server = require("./server");
var router = require('./router');
var requestHandlers = require('./requestHandlers');
// Routes
var handle = {}
handle['/'] = requestHandlers.home;
server.start(router.route, handle)
server.js(启动服务器,这是我要配置服务器的地方,从 URL 获取路径名,并将其传递给路由模块)
var http = require("http");
var url = require('url');
var express = require('express');
function start (route, handle) {
var onRequest = function(request, res) {
var pathname = url.parse(request.url).pathname;
console.log("request for " + pathname + " recieved.");
route(handle, pathname, res);
}
var app = express.createServer(onRequest).listen(8888);
if (app.configure) {
console.log('app exists'); //logging correctly
}
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); //logs correct with 8888 and development
}
exports.start = start;
router.js(从 index --> server 传递的函数 route 调用 router.js 中的 route 函数,调用与句柄对象中的路径名匹配的 requestHandler)
function route (handle, pathname, res) {
console.log("About to route a request for" + pathname); //About to route a request for/stylesheets/style.css SEE BELOW******* this is the error
if (typeof handle[pathname] === 'function') {
handle[pathname] (res);
}
else {
console.log('no request handler found for' + pathname);
}
}
exports.route = route;
requestHandler.js(与 res/req 对象交互,函数映射到某些路径名,仅在请求这些路径名时才调用,这要归功于路由器)
var home = function(res){
res.render('index', { title: 'WWYB?' });
console.log('homepage rendered'); //correctly logs for pathname = '/'
//click();
};
exports.home = home;
** *当我去请求 localhost:8888 时,它会尝试发出一堆请求。首先它正确地请求“/”,然后继续记录所有说“关于路由/stylesheets/style.css”的请求最终页面加载时没有css。我的 layout.jade 文件中指示的路径名正是“/stylesheets/style.css”。
为什么路径名总是评估为 /stylesheets/style.css?我认为节点正在后台做某事,我不完全理解。
如果您需要更多信息,请告诉我。谢谢!