如何在Node.Js中启用HTTP/2.0?

不言
不言原创
2019-03-21 14:20:173148浏览

node-http2是一个节点模块,为nodejs应用程序提供HTTP/2协议的客户端和服务器实现。此节点API与扩展支持HTTP/2的节点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

创建node服务器

让我们创建一个支持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服务器

让我们使用以下命令启动node.js服务器。它将在系统的端口8000上启动Web服务器。

$ node http2-server.js

并在端口8000上访问localhost。

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的node.js教程视频栏目!

以上就是如何在Node.Js中启用HTTP/2.0?的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。