LoginSignup
3
3

More than 5 years have passed since last update.

Node.js簡易HTTPサーバー ログつき

Last updated at Posted at 2018-09-28

コード

HTTPサーバー置きたい場所に下記を置いて実行

app.js
const app = require('connect')();
const morgan = require('morgan');
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer"'));
app.use(require('serve-static')(__dirname))
app.listen(3000);
 $ npm install connect serve-static morgan
 $ node app.js

他のターミナルから curl localhost:3000 とか叩くと

 $ node app.js
::1 - - [28/Sep/2018:12:40:16 +0000] "GET / HTTP/1.1" 404 139 "-"

こんなログが出る(ログフォーマットの詳細はこちらを)

確認環境

Node v8.11.1
connect@3.6.6
serve-static@1.13.2
morgan@1.9.1
Mac OS 10.13.4

Node.jsは公式(https://nodejs.org/en/ ) からインストーラー(LTSを選択)
その後下記ターミナルからコマンド叩いてインストール
npm install connect serve-static morgan

リクエストHTTPヘッダー見たい

こう書き換える

app.js
const app = require('connect')();
const morgan = require('morgan');
morgan.token('rawHeaders', function (req, res) {
  return JSON.stringify(req.headers)
})
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" :rawHeaders'));
app.use(require('serve-static')(__dirname))
app.listen(3000);

JSON形式で出力

 $ node node app.js
::1 - - [28/Sep/2018:12:42:45 +0000] "GET / HTTP/1.1" 404 139 "-" {"host":"localhost:3000","user-agent":"curl/7.54.0","accept":"*/*"}

ユースケース

OpenAPIのモックサーバー立てて開発してた時にこれを組み込んでた。

3
3
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
3
3