您的位置:首页 > 理论基础 > 计算机网络

Node.js中的HTTPS示例

2016-05-24 13:52 441 查看
 

需要openssl的支持, openssl本身不提供windows的安装程序,可以按照如下的步骤进行安装:
(参考https://conetrix.com/Blog/how-to-install-openssl-on-windows-7,并复制到下面)

How-to Install OpenSSL on Windows 7

Download and run the Cygwin installer from their web site:www.cygwin.com.  OpenSSL is not one of that packages that gets installed by default with Cygwin.  The important part of install is choosing OpenSSL as one of the packages you install, because that package is not selected by default.  You do this by searching for "openssl" on the "Select Packages" step, expanding "Net" option, clicking on the "Skip" image so that a version shows, and clicking the "Next" button.  Use the image below as a reference. [more] 



 

安装完后,在cygwin的bin目录下就可以找到openssl.exe.

写如下的node.js文件。

var https = require('https'),

pem = require('pem');

 

pem.config({

pathOpenSSL: 'C:\\cygwin64\\bin\\openssl.exe'

});

 

pem.createCertificate({days:1, selfSigned:true}, function(err, keys){

https.createServer({key: keys.serviceKey, cert: keys.certificate}, function(req, res){

res.end('o hai!')

}).listen(843);

});

 

如果是linux则不需要pem.config,由于windows下openssl所在的路径不是node.js默认查找的路径,所以需要pem.config.

其他情况下如果openssl的路径不对,也需要pem.config.

如果找不到pem模块,需要运行npm install pem 进行安装。

 

运行该文件,然后访问https://localhost:843,就可以看到o hi的结果了。

更多node.js SSL的配置见这里: https://nodejs.org/api/https.html

上面的例子用的是自己创建的证书,所以访问的时候会有证书警告。

如果用的是公网可用的证书,则需要参考https://nodejs.org/api/https.html的例子。比如:

const https = require('https');
const fs = require('fs');
 

const options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),

cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')

};
 

https.createServer(options, (req, res) => {
res.writeHead(200);

res.end('hello world\n');

}).listen(8000);
 

或者

const https = require('https');


const fs = require('fs');


 

const options = {


pfx: fs.readFileSync('server.pfx')


};


 

https.createServer(options, (req, res) => {


res.writeHead(200);


res.end('hello world\n');


}).listen(8000);


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: