Express本地测试HTTPS的示例代码
我的环境
- 亚马逊(AWS)的一个ubuntu虚拟机.
- node
- openssl
生成证书
输入如下命令会在你的当前文件夹生成localhost.key和localhost.cert.
opensslgenrsa-outlocalhost.key2048 opensslreq-new-x509-keylocalhost.key-outlocalhost.cert-days3650-subj/CN=localhost
其中localhost为域名.想要换成别的域名就直接把上面的所有localhost替换成你的域名.
以我为例,我的虚拟机的域名是xxx.compute.amazonaws.com,就以这个域名替换上面所有的localhost,会生成,ec2-34-220-96-9.us-west-2.compute.amazonaws.com.key和ec2-34-220-96-9.us-west-2.compute.amazonaws.com.cert两个文件.
更新
opensslreq-x509-newkeyrsa:4096-keyoutkey.pem-outcert.pem-days365
如果不想用密码保护私钥,加上-nodes.
加上-subj'/CN=localhost'可以设置certificate的内容.将其中的localhost替换成你的域名.
参考:Howtocreateaself-signedcertificatewithopenssl?
代码
想要运行如下代码,需要先安装包
npminit npmi-Shttpsexpress
创建文件index.js,内容如下.
#!/usr/bin/envnode varhttps=require('https'); varfs=require('fs'); varexpress=require('express'); varhost='xxx.compute.amazonaws.com';//Inputyoudomainnamehere. varoptions={ key:fs.readFileSync('./'+host+'.key'), cert:fs.readFileSync('./'+host+'.cert'), requestCert:false, rejectUnauthorized:false }; varhttpApp=express(); varapp=express(); app.get('/',function(req,res){ res.send('hiHTTPS'); }); httpApp.get('/',function(req,res){ res.send('hiHTTP'); }); httpApp.listen(80,function(){ console.log('httpon80'); }); varserver=https.createServer(options,app); server.listen(443,function(){ console.log('httpson443'); });
启动服务器
sudonodeindex.js
访问
浏览器中输入http://xxx.compute.amazonaws.com/就会以80端口访问HTTP服务器.显示hiHTTP.
输入https://xxx.compute.amazonaws.com/就会以443端口访问HTTPS服务器,显示hiHTTPS.
参考
Self-Signed,TrustedCertificatesforNode.js&Express.js
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。