首页 > Web开发 > 详细

Express本地测试HTTPS

时间:2020-09-16 18:16:55      阅读:70      评论:0      收藏:0      [点我收藏+]

我的环境

  • 亚马逊(AWS)的一个ubuntu虚拟机.
  • node
  • openssl

生成证书

输入如下命令会在你的当前文件夹生成localhost.key和localhost.cert.

openssl genrsa -out localhost.key 2048
openssl req -new -x509 -key localhost.key -out localhost.cert -days 3650 -subj /CN=localhost

其中localhost为域名. 想要换成别的域名就直接把上面的所有localhost替换成你的域名.

以我为例, 我的虚拟机的域名是xxx.compute.amazonaws.com, 就以这个域名替换上面所有的localhost, 会生成, ec2-34-220-96-9.us-west-2.compute.amazonaws.com.keyec2-34-220-96-9.us-west-2.compute.amazonaws.com.cert两个文件.

更新
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

如果不想用密码保护私钥, 加上-nodes.

加上-subj ‘/CN=localhost‘可以设置certificate的内容. 将其中的localhost替换成你的域名.

参考: How to create a self-signed certificate with openssl?

代码

想要运行如下代码, 需要先安装包

npm init
npm i -S https express

创建文件index.js, 内容如下.

#!/usr/bin/env node

var https = require(‘https‘);
var fs = require(‘fs‘);
var express = require(‘express‘);

var host = ‘xxx.compute.amazonaws.com‘; // Input you domain name here.
var options = {
    key: fs.readFileSync( ‘./‘ + host + ‘.key‘ ),
    cert: fs.readFileSync( ‘./‘ + host + ‘.cert‘ ),
    requestCert: false,
    rejectUnauthorized: false
};

var httpApp = express();
var app = express();
app.get(‘/‘, function (req, res) {
  res.send(‘hi HTTPS‘);
});
httpApp.get(‘/‘, function (req, res) {
  res.send(‘hi HTTP‘);
});
httpApp.listen(80, function () {
  console.log(‘http on 80‘);
});
var server = https.createServer( options, app );

server.listen( 443, function () {
    console.log( ‘https on 443‘ );
} );

启动服务器

sudo node index.js

访问

浏览器中输入http://xxx.compute.amazonaws.com/就会以80端口访问HTTP服务器. 显示hi HTTP.

输入https://xxx.compute.amazonaws.com/就会以443端口访问HTTPS服务器, 显示hi HTTPS.

参考

Self-Signed, Trusted Certificates for Node.js & Express.js



作者:柳正来
链接:https://www.jianshu.com/p/3e6292233b5a
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Express本地测试HTTPS

原文:https://www.cnblogs.com/zhishaofei/p/13679772.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!