私はnodejsが初めてです。私は単純な Web サーバーを作成し、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;
}
最適化されていないコードの謝罪。