Easy HTTP/2 Server with Node.js and express.js


What is a HTTP / 2

The TCP/IP protocol of the modern Internet was released in 1975, and this technology was amazing 41 years ago. For the most part since its release, we have used HTTP and its successor HTTP/1.1 for client-server communication. It’s great for delivering the Web, but the way developers build websites today has changed dramatically. There are various links to external resources such as images, CSS files, and JavaScript resources. The number of types of resources will only continue to grow. HTTP/2 is the first major update to the long-performing HTTP protocol in the 15 years since its release in 1991. It was created to optimize modern browsers. Better performance and without the use of complex behaviors such as domain sharding (sending resources across multiple domains) or resource file merging (providing a single large resource rather than multiple small resources)

HTTP/2 is the current web standard, its prototype is Google’s SPDY protocol. It is currently supported by most major browsers, and many web sites have implemented the protocol. For example, Flickr, which accesses Yahoo, uses HTTP/2 (screenshot from July 2016).

Yahoo’s Flickr already uses the ‘HTTP/2’ protocol

Advantages and considerations of HTTP/2

HTTP/2 is no different from HTTP/1.1, you can still use XML-like syntax in the body, use header header fields, status codes, cookies, methods, URLs, and so on. Everything that developers are familiar with can still be used in HTTP/2.

HTTP/2 has the following advantages:

  1. Multiplexing: allows browsers to include multiple requests in a single TCP connection, thereby enabling browsers to request all resources in parallel;
  2. Server push: The Server can push the resource to the browser (such as CSS, JS, Image) before the browser knows that the resource is needed, so as to accelerate the page loading time by reducing the number of requests.
  3. Stream priority: Allows the browser to control the load priority of the resource, for example, the browser requests firstHTMLRender and load the restCSSJSFile;
  4. Header compression:HTTP / 1.1The header of the request always repeats the same content, whileHTTP/2All request headers are forced to be de-compressed;
  5. De Facto Mandatory Encryption: Although encryption is not mandatory, most browsers only support itThe TLS (HTTPS)On theHTTP/2.

While HTTP/2 is not yet fully satisfying some of the demands, it is a clear technological advance until better technology is available. Let’s take a look at what you need to know as a Web developer. Most of the optimizations that apply to HTTP/1.1 become redundant in HTTP/2, and some of them can actually affect site performance over HTTP/2, for example:

  1. Resource file merge;
  2. You should also stop using image sprites, CSS, and JS packaging, because changes to even a few of them will affect the client’s cache. inHTTP/2A better protocol is to use multiple small files rather than one large file.
  3. The authors want front-end build tools such asGruntGulpWebpackWill therefore be abandoned, they makeWebDeveloping higher complexity, high learning curves, and managing project dependencies.
  4. The other one applies toHTTP / 1.1Do not apply toHTTP/2Domain name sharding (to bypass the TCP limit on the number of parallel requests). Although it is not necessarily harmful in all cases, it isHTTP/2It is no longer useful to do so. The reason why the suggestion is notHTTP/2Domain sharding is also used because each domain name brings additional query load. If necessary, it is better to resolve multiple domains to the same IP address, and make sure you use a wildcard certificate or a certificate that integrates multiple domains to reduce the time for domain queries.

For more information about HTTP/2, check out the official website.

Node. Js structures, HTTP / 2

Now, let’s see how to set up HTTP/2 servers using Node.js.

Deployment certificate

Create a new folder and self-issued SSL certificates.

$ mkdir http2-express $ cd http2-express$ openssl genrsa -des3 -passout pass:x -out server.pass.key 2048... $ openssl rsa -passin pass:x -in server.pass.key -out server.keywriting RSA key$ rm server.pass.key$ openssl req -new -key server.key -out server.csr... Country Name (2 letter code) [AU]:USState or Province Name (full name) [Some-State]:California... A challenge password []:... $ openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt

When accessing the server, be sure to select “Advanced” and “Continue to localhost (unsafe)” or set localhost to an exception for unsafe access because the browser does not trust its own certificate by default.

Click Advanced

Click continue to Localhost (unsafe)

Initialization, dependency, entry

Initialize the package.json project via NPM and install dependencies on SPdy and Express:

npm initnpm i express spdy --save

Create the entry file index.js for the application, mainly reference and instantiation

const port = 3000const spdy = require('spdy')const express = require('express')const path = require('path')const fs = require('fs')const app = express()

Define a route for express.js

Implement express.js route

app.get('*', (req, res) => {  res    .status(200)    .json({message: 'ok'})})

Set up the certificate and start the Server

Read the certificate from fs.readfilesync ()

const options = {  key: fs.readFileSync(__dirname + '/server.key'),  cert: fs.readFileSync(__dirname + '/server.crt')}

Then, set the certificate option to the Express object:

spdy  .createServer(options, app)  .listen(port, (error) => {    if (error) {      console.error(error)      return process.exit(1)    } else {      console.log('Listening on port: ' + port + '.')    }  })

Finally, Node. Starts the server

Check the result

View the protocol through the browser’s developer tools, just as we viewed Yahoo’s Flickr protocol.

Click “Developer Tools Check Protocol”

As you can see, implementing HTTP/2 using Node.js and express. js with the node-spdy library is straightforward. In most cases, there is little to no need to change your business code, and presumably your site already uses HTTPS/SSL (unless your server only serves static resources, you should use secure HTTPS/SSL). Even if you don’t use HTTP/2, you can use SPDY instead of HTTP/1.1

Of course, in the context of Node.js, there are many libraries, not just node-spdy that provide HTTP/2 implementations, such as Node-http2

conclusion

HTTP/2 provides more and better benefits without using complex optimization techniques. Start enjoying these benefits of HTTP/2. Look forward to the bright future!

PS: This article source code address at http2-Express

WeChat exceptional

Alipay rewards

  • Amos Zhong
  • Links to this article: Biaomingzhong. Making. IO / 2017 / http2 -…
  • Copyright Notice: All articles on this blog are licensed under a CC BY-NC-SA 3.0 license unless otherwise stated. Reprint please indicate the source!

Did this article help you? Welcome to join the front End learning Group wechat group: