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); |
相关文章推荐
- 网络摄像头实时获取信息
- 分配问题[网络流24题之18]
- AsyncHttpClient请求网络数据小节!
- HttpServletRequestWrapper Filter中装饰Request 解决全站编码问题!
- HttpServletRequestWrapper Filter中装饰Request 解决全站编码问题!
- HttpServletRequestWrapper Filter中装饰Request 解决全站编码问题!
- HttpServletRequestWrapper Filter中装饰Request 解决全站编码问题!
- 网络 基于UDP协议的socket编程
- Android 网络通信框架Volley简介
- 骑士共存问题[网络流24题之24]
- 图解Windows网络命令使用实例
- Nutch抓取插件-HTTPS协议支持
- 图解http-ping使用
- Android从网络上获取图片的两种方式
- TCP 和UDP 的区别
- 浅说http
- iOS开发之适配IPV6更新网络处理为AFNetworking3.x, 集成以及遇到的一些问题总结。
- http服务器与cgi交互过程
- 网络虚拟化技术与应用场景
- Http 篇