URLの解析
URLの解析には、URL標準モジュールを利用します(リスト5)。
// URLモジュールの読み込み
var url = require('url');
...
var listener = function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
response.write('第2引数なし\n')
response.write(util.inspect(url.parse(request.url)));
response.write('\n第2引数がtrue\n')
response.write(util.inspect(url.parse(request.url,true)));
response.end();
};
ブラウザから、「http://127.0.0.1:8124/foo/bar?name=statemachine&age=18」にアクセスしてみましょう。リスト6の実行結果が得られます。
url : /foo/bar?name=statemachine&age=18
第2引数なし
{ search: '?name=statemachine&age=18',
query: 'name=statemachine&age=18',
pathname: '/foo/bar',
path: '/foo/bar?name=statemachine&age=18',
href: '/foo/bar?name=statemachine&age=18' }
第2引数がtrue
{ search: '?name=statemachine&age=18',
query: { name: 'statemachine', age: '18' },
pathname: '/foo/bar',
path: '/foo/bar?name=statemachine&age=18',
href: '/foo/bar?name=statemachine&age=18' }
request.urlをparseメソッドに渡すと解析結果が返却されます。第2引数にtrueを渡すと、クエリ文字列を「キー名=値」のハッシュに分解します(太字部分が異なります)。
ホスト名を含んだ形でも解析できます。リスト7は、コンソール上で解析した結果です。
> util.parse('http://127.0.0.1:8124/foo/bar?name=statemachine&age=18#hash')
{ protocol: 'http:',
slashes: true,
host: '127.0.0.1:8124',
port: '8124',
hostname: '127.0.0.1',
href: 'http://127.0.0.1:8124/foo/bar?name=statemachine&age=18#hash',
hash: '#hash',
search: '?name=statemachine&age=18',
query: 'name=statemachine&age=18',
pathname: '/foo/bar',
path: '/foo/bar?name=statemachine&age=18' }
各プロパティの詳細については、Node.jsのドキュメントを参考にしてください。
POSTリクエストを処理する
クライアントからデータを受け取る場合は、http.ServerRequestオブジェクトのイベントをハンドルします。リスト8は、POSTリクエストの処理部分の抜粋です。
if(request.url == '/') {
//(1)フォームの表示
response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
response.end('<html> <form action="/post" enctype="application/x-www-form-urlencoded" method="post">'
+ '名前:<input type="text" name="name"><br>'
+ '年齢:<input type="text" name="age"><br>'
+ '<input type="submit" value="送信">'
+ '</form><html>'
);
} else if(request.url == '/post' && request.method == 'POST') {
//(2)POSTデータのエンコード設定
request.setEncoding('utf8');
//(3)POSTデータの受信
var postdata = "";
request.on('data', function(chunk) {
postdata += chunk;
});
//(4)POSTデータ受信後の処理
request.on('end', function() {
response.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
var query = querystring.parse(postdata)
response.write(util.format('名前:%s\n',query.name))
response.write(util.format('年齢:%s\n',query.age))
response.write(util.format('%j\n', query));
response.end();
});
はじめにサンプルを実行し、ブラウザでアクセスしてみましょう。図1のようなフォームが表示されます。名前と年齢を入力し[送信]ボタンをクリックします。
(1)でURLとメソッドを判定してPOSTリクエストの処理を実行します。送信されてくるデータは、(3)のようにdataイベントをハンドルすることによって受信します。データは1度に送信されてくるわけではなく、チャンク(データの塊)として送信されるため、データの連結が必要です。(2)のsetEncodingメソッドによってエンコーディングを指定しているため、ここでは文字列が渡ってくるため、単純に連結していきます。
(3)最後にendイベントが発生します。ここでは、連結されたデータをquerystringクラスのparseメソッドによって分解し表示しています。実行例は図2の通りです。
