使用Express如何实现本地测试HTTPS

发布时间:2021-04-07 17:36:27 作者:Leah
来源:亿速云 阅读:265

使用Express如何实现本地测试HTTPS?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

生成证书

输入如下命令会在你的当前文件夹生成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.key ec2-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.

关于使用Express如何实现本地测试HTTPS问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. 12C EM express https 连接报错
  2. 本地Spring Boot项目支持https

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

express https

上一篇:使用Python怎么对json文件进行读写

下一篇:怎么在AJAX中利用Servlet处理数据并显示

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》