POSTを受け取る
またまたちょっとしたHTTPサーバを書いてみたのですよ。
今回はPOSTのデータを受け取って表示するだけです。
環境:OS X 10.7.2 / node.js 0.8.8
ソースコードは以下のような感じ。
var http = require('http'), dataSection = require('data-section'), server = http.createServer(); dataSection.get('index.html', function (err, data) { if (err) { throw err; } server.on('request', function (req, res) { if (req.method === 'POST' && req.url === '/post') { var postData = ''; req.setEncoding('utf8'); req.on('data', function (data) { postData += data; }); req.on('end', function () { res.writeHead(200, { 'content-type': 'text/plain; charset=utf8' }); res.end('post data is :' + postData); }); } else { res.writeHead(200, { 'content-type': 'text/html; charset=utf8' }); res.end(data); } }); server.listen(3000); }); /*__DATA__ @@ index.html <!DOCTYPE html> <meta charset="utf-8"> <title>テスト</title> <form action="/post" method="post"> aaa:<input type="text" name="aaa" size="40"><br> bbb:<input type="text" name="bbb" size="40"><br> ccc:<input type="text" name="ccc" size="40"><br> <input type="submit" value="送信"> </form> __DATA__*/
実行するには以下のコマンドを。
$ npm install data-section $ node app.js
このサーバにアクセスすると、入力欄が3つと送信ボタンがあるページが開かれます。
で、入力欄になにかしら入力して送信ボタンを押すと、入力されたデータが表示されます。ただそれだけ。
node.jsだとこういう低レイヤーみたいなところに触れられて良いかも。理解が進む感じ。