POSTを受け取る その2
POSTを受け取る - 四角革命前夜を以前作ったリクエストハンドラもどきで実装したやつ。
app.js
#!/usr/bin/env node var http = require('http'), server = http.createServer(), rh; function RequestHandler() { this._fn = []; } RequestHandler.prototype = { execute: function(req, res) { this._fn.some(function (fn) { return (fn(req, res, function () { return false; }) === void 0); }); }, use: function() { var that = this; Array.prototype.slice.call(arguments).forEach(function (fn) { (typeof fn === 'function') && that._fn.push(fn); }); } }; rh = new RequestHandler(); rh.use( require('./handler/post'), require('./handler/get') ); server.on('request', function(req, res) { rh.execute(req, res); }); server.listen(3000);
handler/get.js
var dataSection = require('data-section'); module.exports = function (req, res, next) { var responseData = dataSection.getSync('index.html'); res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(responseData); return next(); }; /*__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__*/
handler/post.js
module.exports = function(req, res, next) { var postData = ''; if (req.method === 'POST' && req.url === '/post') { req.setEncoding('utf8'); req.on('data', function(data) { postData += data; }); req.on('end', function() { res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }); res.end(decodeURI(postData)); }); } else { return next(); } };
実行する
$ npm install data-section $ node app.js
あとは、普通にブラウザからhttp://localhost:3000/にアクセスするだけ。
使い方は同じ。
微妙に違うところは、日本語を入力するとdecodeURIでちゃんと日本語が表示できるところ、かな。