Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?
@natsuki_summer

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

2
Help us understand the problem. What is going on with this article?
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
natsuki_summer
Webとかネイティブアプリのエンジニアのメモ書き 基本勉強用です
binc
Eコマースプラットフォーム「BASE」、オンライン決済サービス「PAY.JP」、購入者向けID型決済サービス「PAY ID」の3つのサービスを運営しています。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
2
Help us understand the problem. What is going on with this article?