LoginSignup
26
27

More than 5 years have passed since last update.

Node.jsのWebサーバ基本処理

Posted at

1.動作確認

httpのcreateServerを使うだけ。
listenにポート指定してやればよい。

var http = require("http");

http.createServer(function(request, response) {
    response.writeHead(200, {
        "Content-Type": "text/plain"
    });
    response.write("Hello World");
    response.end();
}).listen(8888);

2.リクエスト情報取得

requestはIncomingMessageのインスタンス。
つまり、Readable Streamインタフェースを持つので情報を取得する場合は'data'イベントを追加してやればよい。
処理の終了時に'end'イベントを指定しておく。

var http = require("http");
var querystring = require("querystring");

http.createServer(function(request, response) {
    var postData = "";

    request.on("data", function(chunk) {
        postData += chunk;
    });
    request.on("end", function() {
        res.writeHead(200, {"Content-Type": "text/plain"});
        res.write("POST DATA is " +  querystring.parse(postData).text);
        res.end();
    });
}).listen(8888);

26
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
27