Last active
September 19, 2022 16:29
-
-
Save zakuroishikuro/9542944 to your computer and use it in GitHub Desktop.
HTTPリクエストをオウム返しするサーバ (Node.js勉強中)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Node.js勉強中...HTTPリクエストをオウム返しするサーバを作ってみた | |
// http://qiita.com/manuluu/items/dd871a5a98e695b9129e | |
var http = require('http'); | |
// サーバ作る | |
var server = http.createServer(function(req, res) { // HTTPリクエスト受けたら実行されるメソッド | |
var req_str = ""; | |
// 読む (リクエスト行) | |
req_str += [req.method, req.url, "HTTP/" + req.httpVersion].join(" ") + "\n"; | |
// 読む (ヘッダ行) | |
var header_lines = []; | |
var headers = req.headers; | |
for (var key in headers) | |
header_lines.push(key + ": " + headers[key]); | |
req_str += header_lines.sort().join("\n") + "\n"; | |
// 読む (ボディ) | |
var body_str = ""; | |
req.on('data', function(chunk){ body_str += chunk }); // ボディ読み込んでるメソッド | |
req.on('error', function(e) { console.log('problem with request: ' + e.message) }); | |
// 書く | |
req.on('end', function(){ // ボディ読み終わったら実行されるメソッド | |
var result = req_str; | |
if (body_str) result += "\n" + body_str; | |
// レスポンス返す | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
res.end(result); // レスポンス返して終わり。ボディ読む前に閉めちゃうと読めない | |
// コンソールにも出力 | |
console.log("========== Received Request ========== count: " + count); | |
console.log(result); | |
if (body_str) { // ボディはそのままじゃ読みづらいので整形したものも出力 | |
console.log("********** Parsed Body ********** count: " + count); | |
console.log(require('querystring').parse(body_str)); | |
} | |
}); | |
count++; | |
}); | |
//サーバ起動 | |
var host = '127.0.0.1'; | |
var port = 2501; | |
server.listen(port, host); | |
console.log('Server running at http://%s:%d/', host, port); | |
var count = 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment