2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nodeでhttp2を試す

Posted at

ローカルホストでhttp2の動作を見るには、まず証明書を作成する必要がある

openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' -keyout localhost-privkey.pem -out localhost-cert.pem

そうすると、http2でサーバを動かせる

const http2 = require('http2')
const fs = require('fs')

const { PORT = 8443 } = process.env

const server = http2.createSecureServer({
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem')
})
server.on('error', err => console.error(err))

server.on('stream', (stream, headers) => {
  stream.respond({
    'content-type': 'text/html',
    ':status': 200
  })
  stream.end('<h1>Hello World</h1>')
})

server.listen(PORT, () => {
  console.log(`https://localhost:${PORT}`)
})

http2をブラウザで確認するには、ChromeのDevtoolのネットワークタブを右クリックしてPriorityとProtocolと有効にする。
Protocolがh2であればhttp2で通信していることが確認できる。

また、HTTP/2 and SPDY indicator - Chrome ウェブストアを使うことでどのアプリケーションがhttp2で動作しているかすぐに確認できるので、便利。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?