Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

コード

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のモックサーバー立てて開発してた時にこれを組み込んでた。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away