热门搜索 :
考研考公
您的当前位置:首页正文

Express本地测试HTTPS

来源:东饰资讯网

我的环境

  • 亚马逊(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替换成你的域名.

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

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

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

代码

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

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 =  // 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

访问

参考

Top