LoginSignup
2
1

More than 5 years have passed since last update.

connectを使って静的なHTTPサーバーを実装する

Last updated at Posted at 2015-08-03

目標

connectを使って静的なファイルを配信するHTTPサーバーを作ります。

使うもの

serve-staticを使います。
serveStaticはローカルに存在するファイルを返すmiddlewareです。

注意事項

昔のconnectは同様のmiddlewareを組み込み(staticプロパティ)で提供していました。
version 3.0以降、組み込みmiddlewareは外部モジュールに分離されました。
2013年頃の技術情報は組み込みモジュールを前提として書かれています、ご注意ください。

ソースコード

index.html
hello world
index.js
const http = require('http')
const connect = require('connect')
const serveStatic = require('serve-static')

const app = connect()
  .use(serveStatic('.')) // 静的ファイルの置き場を指定します。

http.createServer(app).listen(3000)

ライブラリをインストール

npm i connect serve-static

サーバーを起動

node .

動作確認

curl 'http://localhost:3000'

hello worldが表示されます。

詳細なレスポンス

curl 'http://localhost:3000/' -v
* * Hostname was NOT found in DNS cache
*   Trying ::1...
* Connected to localhost (::1) port 3000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.37.1
> Host: localhost:3000
> Accept: */*
>
< HTTP/1.1 200 OK
< Accept-Ranges: bytes
< Cache-Control: public, max-age=0
< Last-Modified: Wed, 29 Jul 2015 01:12:48 GMT
< ETag: W/"d-14ed75e7280"
< Content-Type: text/html; charset=UTF-8
< Content-Length: 13
< Date: Wed, 29 Jul 2015 01:22:06 GMT
< Connection: keep-alive
<
hello world
* Connection #0 to host localhost left intact

HTTPヘッダーをいい感じに設定してくれます。

存在しないファイルを要求

curl 'http://localhost:3000/a.html -v'

404レスポンスを返します。

* Hostname was NOT found in DNS cache
*   Trying ::1...
* Connected to localhost (::1) port 3000 (#0)
> GET /a.html HTTP/1.1
> User-Agent: curl/7.37.1
> Host: localhost:3000
> Accept: */*
>
< HTTP/1.1 404 Not Found
< X-Content-Type-Options: nosniff
< Content-Type: text/html; charset=utf-8
< Content-Length: 19
< Date: Wed, 29 Jul 2015 01:21:13 GMT
< Connection: keep-alive
<
Cannot GET /a.html
* Connection #0 to host localhost left intact

合わせて読みたい

2
1
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
2
1