LoginSignup
112
117

More than 3 years have passed since last update.

Node.jsによる必要最小限のhttpサーバとhttpsサーバとhttp proxyサーバ

Last updated at Posted at 2013-08-29

Node.js

勉強のためにNode.jsで必要最小限の httpサーバhttpsサーバhttp proxyサーバ を書いてみた。

httpサーバ

これは最初に目にすることになると思う。
初めに開く Node.jsとは? - nodejs.org/ja (以前はnodejs.jp) に書いてあるので。

http-server-simple.js
const http = require('http');
http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, () => console.log('Server http://localhost:3000'));

テキストの Hello World しか返せないので役に立つわけではない。
あくまでHello Worldである。
5行で書けるんですよね。Webサーバが。

httpsサーバ

上記の httpサーバ を、そのまま httpsサーバ にしてみた。

https-server-simple.js
const https = require('https'), fs = require('fs');
const options = {pfx: fs.readFileSync('secure.pfx'),
               passphrase: 'passphrase'};
https.createServer(options, (req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, () => console.log('Server https://localhost:3000'));

pfxファイル secure.pfx は なんとか自分で用意してください。
私は無料の Visual Studio 2012 Express for Windows Desktop
を使って、Project の「プロパティ」、「署名」の「テスト証明書の作成」で
いわゆるオレオレ証明書を作成しました。

http proxy サーバ

一番簡単な http proxyサーバ を無理やり10行で書いてみた。(笑

http-proxy-server-in-10-lines.js
const http = require('http'), url = require('url');
http.createServer((cliReq, cliRes) => {
  const x = url.parse(cliReq.url);
  const opt = {host: x.hostname, port: x.port || 80, path: x.path,
             method: cliReq.method, headers: cliReq.headers};
  const svrReq = http.request(opt, svrRes => {
    cliRes.writeHead(svrRes.statusCode, svrRes.headers);
    svrRes.pipe(cliRes); });
  cliReq.pipe(svrReq);
}).listen(8080);

なぜ10行で書いたかというと、20行で書いたという
こういう記事 (A HTTP Proxy Server in 20 Lines of node.js Code) を見つけてしまったからだ。
でも、後で探したら stackoverflow (simple proxy server that works on a node.js host like appfog) にも、ほぼ同じようなコードが出てたんですよね。
まぁ、誰にでも到達できるコードだという事ですね。
でも、http, stream, など基本的な事がわかっていないと書けないですよね。

一応書いてみたものの https は通せないし、WebSocket なども通らないんですよ。
簡単じゃない事がわかった。
もちろん自分で書かずに http-proxy - npm, node-http-proxy - http-party - GitHub などを使うのもいいよね。

勉強してみると、CONNECTメソッドやらUpgradeやら、
いろいろと対応しないとダメらしい。
今度はそれを書くぞ。
それではまた。

Gist にも一緒に投稿してみた。

https もサポートする http proxy サーバ

[追記] こちらに続きの記事を書きました。

Node.js で https をサポートする http proxy サーバを 80行で書いた

112
117
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
112
117