4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

URLルーティングのコードの意味をメモしとく

簡単なURLルーティング


   var http=require('http');
   var path=require('path');
var server=http.createServer();
server.on('request',function(req,res){
var lookup=path.basename(decodeURI(req.url));
res.writeHead(200,{"Content-Type":"text/plain"});
res.write(lookup);
res.end();
}).listen(4000);
console.log("Server is moving");

解説

  • path:ファイルのパスに対する処理や変換を行う。ほとんどのメソッドは文字列の変換だけを行う。パスが正しいかを検証するためにファイルシステムに尋ねる事はない
  • path.basename:パスの最後の要素を返す。localhost:4000/alissaなら「alissa」が返される。req.urlなら「/alissa」となる
    • ただし上記だと/alissa/angelaはエラーとなってしまう。その回避方法は後述
  • decodeURI:URLエンコードをデコード。例→locallhost:4000/alissa white grluzでリクエストするとデコードしていれば「alissa white grluz」で評価されるが、デコードしなければ「alissa%20white%20grluz」として評価され、エラーとなる。*%20はURLエンコードされたから半角スペース文字列。ただし半角スペースをファイル名に用いない方が賢明である。
  • 複数階層コンテンツのルーティング

    
     var http=require('http');
    var path=require('path');
    var server=http.createServer();
    var pages=[
    {route:'/',output:'woohoo!'},//routeに/を追加
    {route:'/about/alissa',output:"アリッサ可愛い!"},
    {route:'/about/node',output:'node.js'},
    {route:'/another page',output:function(){return 'これが'+this.route;}}
    ];
    server.on('request',function(req,res){
    var lookup=decodeURI(req.url);//basenameの代わりにreq.urlを渡す
    pages.forEach(function(page){
    if(page.route===lookup){
    res.writeHead(200,{"Content-Type":"text/plain"});
    res.write(typeof page.output==='function' ? page.output():page.output);
    res.end();
    }
    });
    if(!res.finished){
    res.writeHead(404);
    res.write('ぺーじがみつからない!');
    res.end();
    }
    }).listen(4000);
    console.log("Server is moving");
    

    解説

    • basenameを削除で複数階層のパスに対応:それだけで複数階層コンテンツのルーティングが可能になる。
    • コードの結果は次の通り
      
        localhost:4000→woohoo!
        localhost:4000/about/alissa→アリッサ可愛い!
       localhost:4000/about/node→node.js
        localhost:4000/another pagey→これが/another page
      
    • アリッサとアンジェラ:アリッサ・ホワイト・グラズとはTHE AGONISTの初代ヴォーカリストで現在はARCH ENEMYのヴォーカリスト(3代目)。アンジェラ・ゴソウは元ARCH ENEMYの2代目ヴォーカリスト←Node.jsとは関係ありません
4
6
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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?