摘要:本篇Node.js教程 就将会大家讲解HTTPS示例的相关内容,感兴趣的同学可以一起动手操作一下。
本篇Node.js教程 就将会大家讲解HTTPS示例的相关内容,感兴趣的同学可以一起动手操作一下。
1.
需要openssl的支持, openssl本身不提供windows的安装程序,可以按照如下的步骤进行安装:
2.
(参考https://conetrix.com/Blog/how-to-install-openssl-on-windows-7,并复制到下面)
3.
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.
1.写如下的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 进行安装。
1.运行该文件,然后访问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);
希望这篇文章可以帮助到你。总之,同学们,你想要的职坐标IT频道都能找到!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号