工具微信支付Nodejs/js

Nodejs+Express创建HTTPS服务器

2015-09-05  本文已影响20679人  我是7号_frank

终于有时间整理了。。。

为了使我的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申请证书,一般免费证书很少,需要交费。

2. 使用Express创建Https服务器

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

#生成私钥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: 证书文件
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访问

查看证书:


查看证书

由于我们证书是自己创建的,没有经过第三方机构的验证,所以会出现警告的提示。有条件的可以去godaddy SSL Cert官网申请,当然挺贵的,免费党就选择了WoSign,也是可以的,详情见[https://weixin.frankfan.me]

WoSign验证证书

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

参考:
http://blog.fens.me/nodejs-https-server/
http://heyrod.com/snippet/s/node-https-ssl.html

上一篇 下一篇

猜你喜欢

热点阅读