我是nodejs的新手。我一直在尝试编写一个简单的网络服务器并呈现 html 页面。我不想在这个阶段使用 Express 或其他框架,因为我正试图深入了解。
我的问题是:在启动服务器后第一次加载页面时,它加载了响应的默认值。之后在每次交替加载时,它都会显示默认页面(404 Not Found)和正确的 HTML。
这是第一次加载时的服务器日志(当显示“默认”作为响应时):
- 请求 url / 收到
- 即将路由请求/
- 这是主页
- 内容类型文本/html
- 文件读取完成...
刷新时,服务器日志完全相同,但显示的是实际页面。
在进一步刷新时,我得到 404 Not Found,这是我的路由器的默认情况。服务器日志再次相同。
这是 server.js 代码:
var http = require('http');
var url = require('url');
function start(route){
function onRequest(request, response){
var pathname = url.parse(request.url).pathname;
console.log('request for url '+pathname+' received');
resp = route(pathname);
console.log('content-type '+resp['ctype']);
response.writeHead(200, {'Content-Type':resp['ctype']});
response.write(resp['file'].toString());
response.end();
}
http.createServer(onRequest).listen(8888);
console.log('Server Has Started');
};
exports.start = start;
这是路由器代码:
var fs = require('fs'),
datafile={'file':'default', 'ctype':'text/html'};
function read_html(filename){
fs.readFile(filename, 'utf-8', function(err, data){
if (err){console.log(err);}
else {datafile['file'] = data;console.log('FILE READING FINISHED ...\n');}
});
}
function route(pathname){
console.log('About to route for request '+ pathname);
switch(pathname){
case '/':
console.log('this is the home page');
read_html('./index.html');
datafile['ctype']='text/html';
break;
case '/features':
console.log('this is the FEATURES page');
read_html('./features.html');
datafile['ctype']='text/html';
break;
case '/css/root.css':
console.log('this is the CSS');
read_html('./css/root.css');
datafile['ctype']='text/css';
break;
default:
datafile['file'] = '404 Not Found\n';
datafile['ctype']='text/html';
console.log('404 NOT FOUND');
break;
}
return datafile;
}
为未优化的代码道歉。