var url = require('url');URLを扱うためには、「url」というオブジェクトをロードしておきます。このurlオブジェクトは、URLの文字列をパースし、そこから必要なものを取り出す機能を提供します。
var url_parts = url.parse(request.url);リクエストがアクセスしてきたURLをパース処理します。リクエストされたURLは、requestイベントハンドラの引数に渡されるrequestオブジェクトの「url」というプロパティで得ることができます。
"/":{こんな具合になっていることがわかるでしょう。連想配列には、title、message、contentというキーが用意されており、それぞれ「タイトルテキスト」「ページに表示するメッセージテキスト」「表示するページの内容(テンプレートデータ)」を値として保管してあります。この変数routesから、アクセスするアドレスのパスごとに必要な情報を取り出し処理しよう、というわけです。
"title":"Main Page",
"message":"これはサンプルのページですよ。",
"content":content1 }
if (routes[url_parts.pathname] == null){……}変数url_partsにURLの各要素がオブジェクトとして保管されていましたが、この中で「パス」の値は「pathname」というプロパティとして保管されています。
var content = ejs.render( template,後は、変数routesから必要な値を取り出してレンダリングをするだけです。例えば、titleに設定する値は、
{
title: routes[url_parts.pathname].title,
content: ejs.render(
routes[url_parts.pathname].content,
{
message: routes[url_parts.pathname].message
}
)
}
);
title: routes[url_parts.pathname].titleこのように用意すればいいですし、コンテンツのレンダリングをcontentに用意するには、
content: ejs.render(このようにすればよいでしょう。ここで表示するコンテンツのテンプレートはroutes[url_parts.pathname].contentで得られますから、これをrenderするだけです。
routes[url_parts.pathname].content, ……)
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
var http = require('http'); var fs = require('fs'); var ejs = require('ejs'); var url = require('url'); var template = fs.readFileSync('./template.ejs', 'utf8'); var content1 = fs.readFileSync('./content1.ejs', 'utf8'); var content2 = fs.readFileSync('./content2.ejs', 'utf8'); var routes = { "/":{ "title":"Main Page", "message":"これはサンプルのページですよ。", "content":content1}, "/index":{ "title":"Main Page", "message":"これはサンプルのページですよ。", "content":content1}, "/other":{ "title":"Other Page", "message":"別のページを表示していますよ。", "content":content2} }; var server = http.createServer(); server.on('request', doRequest); server.listen(1234); console.log('Server running!'); // リクエストの処理 function doRequest(request, response) { var url_parts = url.parse(request.url); // route check if (routes[url_parts.pathname] == null){ console.log("NOT FOUND PAGE:" + request.url); response.writeHead(200, { 'Content-Type': 'text/html' }); response.end("<html><body><h1>NOT FOUND PAGE:" + request.url + "</h1></body></html>"); return; } // page render var content = ejs.render( template, { title: routes[url_parts.pathname].title, content: ejs.render( routes[url_parts.pathname].content, { message: routes[url_parts.pathname].message } ) } ); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(content); response.end(); }
<< 前へ | 次へ >> |