如何在Node.js中启用HTTP/2.0

Node-http2是一个node模块,它提供的HTTP/2协议的NodeJS应用的客户端和服务器实现。这个节点API非常类似与HTTP/2扩展支持到 node https 模块。

安装node.js

如果你已经在系统上安装node.js,你可以跳过此步骤。如果在你的系统上没有node.js,使用以下步骤来安装它的命令。
$ sudo apt-get install python-software-properties python g++ make
$ curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -
$ sudo apt-get update
$ sudo apt-get install nodejs
或者你也可以 通过升级NPM Node.js 。

安装Node-http2模块

Node-http2模块下默认NPM库中可用。所以只需要执行下面的命令来安装它为您的应用。
$ npm install http2

创建示例节点服务器

让我们创建一个HTTP / 2支持样本节点服务器。首先创建一个自签名的SSL证书或获得授权的SSL提供商提供有效的SSL。
$ openssl req -x509 -nodes -newkey rsa:2048 -keyout example.com.key -out example.com.crt
现在,创建具有下列内容的http2-server.js文件。
var fs = require('fs');
var options = {
  key: fs.readFileSync('./example.com.key'),
  cert: fs.readFileSync('./example.com.crt')
};

require('http2').createServer(options, function(request, response) {
  response.end('Welcome HTTP/2.0');
  console.log("Server listening on: http://localhost:8000");
}).listen(8000);

启动节点服务器

让我们用下面的命令启动node.js服务器。这将启动8000端口上的Web服务器。
$ node http2-server.js
访问本地主机8000端口,如下。 启用的Node.js HTTP2
赞(52) 打赏
未经允许不得转载:优客志 » 系统运维
分享到:

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏