2016-07-07 17 views

答えて

2

複数の独立した要求ハンドラを作成する上位レベルの方法は、a simple framework like Expressを使用することです。あなたが求めていることを技術的に行う必要はありませんが、Expressはそのようなタスクを容易にするために構築されています。

複数のルートハンドラとシンプルExpressサーバは、次のようになります。

var express = require('express'); 
var app = express(); 

app.get('/', function(req, res) { 
    // handle the/route here 
}); 

app.get('/hello', function(req, res) { 
    // handle the /hello route here 
}); 

app.listen(3000); 

ザ・エクスプレスのフレームワークは、上記のように、あなたが単にルートを追加できるようにするために構築されています。また、あなたの元に厳密に答えて


...などのミドルウェア処理や、Cookie処理、セッション処理、ポスト処理、などのように事前に構築されたミドルウェア・モジュールの多くへのアクセスなど、多くの、より多くの機能が含まれています通常のHTTPモジュールを使用し、既存のリスナーに2番目のルートを追加しない場合は、サーバー上のrequest eventをリッスンすることができます(これは、ルートハンドラを追加する最も簡単な方法ではないと思います)。実際に

var http = require('http'); 

var serverFunction = function(req, res) { 
    if (req.url === '/') { 
     //does something 
    } 
} 

var server = http.createServer(serverFunction).listen(3000); 

server.on('request', function(req, res) { 
    // see all incoming requests here 
    if (req.url === '/hello') { 
     // process /hello route here 
    } 
}); 

あなたがhttp server doc carefullyを読めば、あなたはあなたのserverFunctionrequestイベントのために自動的に登録されたリスナー以外の何ものでもありませんし、イベント形式のインターフェイスを備えたとして、あなたがちょうどそのためのより多くのリスナーを作成できることがわかりますあなたが選ぶならば、イベント。

+0

あなたのソリューションは完璧に機能しました!ありがとう! – leonero

0

低レベルのNodeJS HTTP APIを使用すると仮定します。関数の構成を使用して、複数のハンドラを1つのハンドラにまとめることができます。各ハンドラは、req.urlが一致しない場合は、次のハンドラに実行を渡す必要があります。

var http = require('http'); 

var handler1 = function(req, res) { 
    res.writeHead(200, { 'Content-Type': 'text/html' }); 
    res.write('/'); 
    res.end(); 
} 

var handler2 = function(req, res) { 
    res.writeHead(200, { 'Content-Type': 'text/html' }); 
    res.write('/Hello'); 
    res.end(); 
} 

var middleware = compose([wrapHandler('/', handler1), 
         wrapHandler('/hello', handler2)]); 

http.createServer(middleware).listen(3000); 

function wrapHandler(path, cb) { 
    return function (req, res, next) { 
     if (req.url === path) { 
      cb(req, res); 
     } else { 
      next(); 
     } 
    }; 
} 

function notFoundHandler(req, res) { 
    res.writeHead(404, { 'Content-Type': 'text/html' }); 
    res.write('No Path found'); 
    res.end();  
}; 

// adapted from koa-compose 
function compose(middleware) { 
    return function (req, res){ 
     let next = function() { 
      notFoundHandler.call(this, req, res); 
     }; 

     let i = middleware.length; 
     while (i--) { 
      let thisMiddleware = middleware[i]; 
      let nextMiddleware = next; 
      next = function() { 
       thisMiddleware.call(this, req, res, nextMiddleware); 
      } 
     } 
     return next(); 
    } 
} 
関連する問題