Express怎样在本地测试HTTPS

php中世界最好的语言
php中世界最好的语言 原创
2018-06-07 09:33:31 1257浏览

这次给大家带来Express怎样在本地测试HTTPS,Express在本地测试HTTPS的注意事项有哪些,下面就是实战案例,一起来看一下。

我的环境

  1. 亚马逊(AWS)的一个ubuntu虚拟机.

  2. node

  3. 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.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('//m.sbmmt.com/m/', function (req, res) {
 res.send('hi HTTPS');
});
httpApp.get('//m.sbmmt.com/m/', 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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

JS操作页面背景变暗

在实战项目中怎样使用jquery layur弹出层

以上就是Express怎样在本地测试HTTPS的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。