LoginSignup
2
2

More than 5 years have passed since last update.

Node.js URLルーティングのテスト

Posted at

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の部分

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2