Nodejs+Express创建HTTPS服务器

转自:https://www.cnblogs.com/handongyu/p/6260209.html

Nodejs+Express创建HTTPS服务器

为了使我的Nodejs服务器提供HTTPS服务,学习了一下如何利用express创建https服务器,现记录如下。(一点一点的积累与掌握吧)


1. 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 = 18080;
var SSLPORT = 18081;

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:18080
    HTTPS Server is running on: https://localhost:18081
  • 打开浏览器

HTTP访问:


HTTP访问

HTTPS访问:


HTTPS访问

查看证书:


查看证书

WoSign验证证书


至此,我们成功的利用Nodejs内置https和express创建了HTTPS服务器。

原文地址:https://www.cnblogs.com/double1/p/13401881.html