Nodejs+Express创建HTTPS服务器

Nodejs+Express创建HTTPS服务器

标签(空格分隔): Node.js


Http与Https

HTTP: 超文本传输协议 (Hypertext transfer protocol) 是一种详细规定了浏览器和万维网服务器之间互相通信的规则,通过因特网传送万维网文档的数据传送协议。
HTTPS:(Hypertext Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HTTP的安全版。即HTTP下加入SSL层,HTTPS的安全基础是SSL,因此加密的详细内容就需要SSL。 它是一个URI scheme(抽象标识符体系),句法类同http:体系。用于安全的HTTP数据传输。https:URL表明它使用了HTTP,但HTTPS存在不同于HTTP的默认端口及一个加密/身份验证层(在HTTP与TCP之间)。这个系统的最初研发由网景公司进行,提供了身份验证与加密通讯方法,现在它被广泛用于万维网上安全敏感的通讯,例如交易支付方面。

区别

https协议需要到ca申请证书,一般免费证书很少,需要交费。
http是超文本传输协议,信息是明文传输,https 则是具有安全性的ssl加密传输协议。
http和https使用的是完全不同的连接方式,用的端口也不一样,前者是80,后者是443。
http的连接很简单,是无状态的;HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议,比http协议安全。

2. 使用Express创建Https服务器

在Nodejs中,我们可以通过内置的https库,来实现HTTPS服务器。

  • 首先,我们需要利用openssl生成证书文件:
#生成私钥key文件
openssl genrsa 1024 > /path/to/private.pem
//
#通过私钥文件生成CSR证书签名
openssl req -new -key /path/to/private.pem -out csr.pem
//
#通过私钥文件和CSR证书签名生成证书文件
openssl x509 -req -days 365 -in csr.pem -signkey /path/to/private.pem -out /path/to/file.crt

新生成了三个文件:

private.pem: 私钥
csr.pem: CSR证书签名
file.crt: 证书文件

  • 修改Nodejs启动文件server.js:
var app = require('express')();
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('/path/to/private.pem', 'utf8'),
var certificate = fs.readFileSync('/path/to/file.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
var PORT = 8000;
var SSLPORT = 8001;

httpServer.listen(PORT, function() {
    console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
httpsServer.listen(SSLPORT, function() {
    console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});

// Welcome
app.get('/', function(req, res) {
    if(req.protocol === 'https') {
        res.status(200).send('Welcome to Safety Land!');
    }
    else {
        res.status(200).send('Welcome!');
    }
});
  • 启动服务器:
$ node server.js
HTTP Server is running on: http://localhost:8000
HTTPS Server is running on: https://localhost:8001
  • 测试

Http 访问:http://localhost:8000

Https 访问: https://localhost:8001

在访问Https的时候会出现如下提示:

Nodejs+Express创建HTTPS服务器_第1张图片
https安全连接.png

这时点击高级——>继续前往localhost(不安全)

注意

通过私钥文件生成CSR证书签名的时候,会有如下提示

Country Name (2 letter code) [AU]:CN

其他的提示都是与公司相关提示,需要根据情况回复

参考文章
Nodejs+Express创建HTTPS服务器

Nodejs创建HTTPS服务器

你可能感兴趣的:(Nodejs+Express创建HTTPS服务器)