またーり作成中

IT、電子工作、裁縫とかとか

Amazon Web Services 基礎からのネットワーク&サーバ構築 #5

CHAPTER5の感想

この章のタイトルは『HTTPの動きを確認する』。章まるごとHTTPでAWSはお休みですね。『HTTPをしゃべってみよう』という章があります。キャッチーですね。大好きです。サーバー側のサンプルjsですが、リンク切れを起こしていましたので下に書いていますが問題あったら消すので言ってください。内容はHTTPプロトコルの基礎です。これはweb系を仕事にしてる場合必須な知識かなと思います。

詳細

var http = require('http');
http.createServer(function(req,res){

    var data ={
        RequestHeader: req.headers
    };

    if(req.method == 'GET'){
        response(res,data);
    }else if(req.method == 'POST'){ 
        req.on('data',function(body) {
            data.RequestBody = body.toString();
            req.on('end',function(){
               response(res,data);
            });
        });
    }
}).listen(8080);

function response(res,data){
    var json = JSON.stringify(data);
      res.writeHead(200,{'Content-Type':'application/json','Content-Length':json.length});
    res.end(json);
}
telnet ec2-xxxxxxxxxxxx.compute-1.amazonaws.com 8080

POST / HTTP/1.0
User-Agent: OreOreAgent
Content-Length: 3

abc
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 87
Date: Sat, 09 Feb 2019 12:31:46 GMT
Connection: close

{"RequestHeader":{"user-agent":"OreOreAgent","content-length":"3"},"RequestBody":"abc"}Connection closed by foreign host.