LoginSignup
8
9

More than 5 years have passed since last update.

Node.js + expressで簡易HTTPサーバを作る

Last updated at Posted at 2014-11-01

目的

コンテンツを置くだけの簡単なHTTPサーバを開発環境上で作る

要件

  • ローカルの開発環境で動作確認にすぐ使える
  • リクエストの時刻をコンソールに出力する(log4jsでできる)
  • HTTP GET, POSTのクエリストリングは処理しない
  • パッケージ化はしない

使ったパッケージ

  • log4js
  • express
  • morgan

構成

/to/app/path
+ SimpleHttpServer.js 実行ファイル
+ public/ コンテンツを格納するフォルダ

パッケージのインストール

$cd /to/app/path
$npm install log4js express morgan
→express4からロギングはmorganとして分離

express

responseはexpressにお任せ.

SimpleHttpServer.js

var PORT=3000,
        ROOTDIR='public';

try {
    var log = require('log4js');
    logger = log.getLogger();
    var morgan = require('morgan');
    logger.info('logger loaded');

    var express = require('express');
    var app = express();

} catch (e) {
    logger.error(e);
} 

app.use(morgan('dev', { format:'dev', immediate: true}));
app.use(express.static(ROOTDIR));

app.use(function(req, res, next) {
     logger.info('request to: ' + req.path);
     next();
});

app.listen(PORT);

app.use(function(){...})でmiddlewareに関数を追加している.
morganはdevレベルでロギングを設定した.

function(){...}の前でパスを省略することで,どのパスでも関数が呼ばれる.
参考:app.use([path], [function...], function)

実行

public/にコンテンツを置いて実行する.

$node SimplerHttpServer.js
[2014-11-22 18:06:46.626] [INFO] [default] - logger loaded
GET /hoge - - ms - -
GET /hogea - - ms - -
GET /hogeb - - ms - -
GET /favicon.ico - - ms - -
[2014-11-22 18:06:52.012] [INFO] [default] - request to: /favicon.ico


(解決済み)追記

コンテンツが存在するURLを指定すると私の環境では表示されません.
存在しないURLだと"request to: ..."が表示されます.

別途,調べてみます.

404などクライアント向けのエラーハンドラだった

app.use(function()...)は404などのエラーの場合のみ実行される.
存在しないURLを指定する場合のみ,"request to: ..."が表示されていたので納得した.

How do you handle 404s?

How do you handle 404s?
In Express, 404s are not the result of an error. Therefore, the error-handler middleware will not capture 404s. This is because a 404 is simply the absence of additional work to do; in other words, Express has executed all middleware / routes, and found that none of them responded. All you need to do is add a middleware at the very bottom (below all others) to handle a 404:

app.use(function(req, res, next){
res.send(404, 'Sorry cant find that!');
});

以上.

8
9
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
8
9