Node.jsの本やサイトを読んである程度の知識はあるものの、浅く広くぐらいしかないからURLルーティングをコードの意味を理解しながら書いてみた。
簡単なURLルーティング
var http=require('http');
var fs=require('fs');
var server=http.createServer();
server.on('request',function(req,res){
switch(req.url){
case '/index.html':
fs.readFile(__dirname+'/index.html','utf-8',function(err,data){
if(err){
res.writeHead(404,{"Content-Type":"text/html"});
res.write('Not found');
return res.end();
}
res.writeHead(200,{"Content-Type":"text/html"});
res.write(data);
res.write(req.url);
res.end();
});
break;
case '/alissa.html':
fs.readFile(__dirname+'/alissa.html','utf-8',function(err,data){
if(err){
res.writeHead(404,{"Content-Type":"text/html"});
res.write('Not found');
return res.end();
}
res.writeHead(200,{"Content-Type":"text/html"});
res.write(data);
res.write(req.url);
res.end();
});
break;
case '/jake.html':
fs.readFile(__dirname+'/jake.html','utf-8',function(err,data){
if(err){
res.writeHead(404,{"Content-Type":"text/html"});
res.write('Not found');
return res.end();
}
res.writeHead(200,{"Content-Type":"text/html"});
res.write(data);
res.write(req.url);
res.end();
});
break;
default:
res.writeHead(404,{"Content-Type":"text/html"});
res.write('Error!');
res.end();
}
}).listen(8000);
console.log('Server is starting');
switch使ってURL別にいちいちどのページに飛ぶかを設定するのはめんどくさい。まあ、モジュールでコードを別ファイルに分けたり、関数とか使えば楽になることは知っているが、今回は基本を理解するうえこんなめんどくて長い文を書いただけ。ストリーム使えばもっと短くなるし。
今回のメモ
①req.urlは「localhost:8000/html_load/index.html」の/index.htmlの部分
②仮に「localhost:8000/html_load/public/index.html」なら/public/index.htmlの部分