初始化

This commit is contained in:
dengtongyu committed 2020-11-23 18:59:26 +08:00
commit 5efd5b9c40
129 files changed
+16739

No files matched your search

@@ -0,0 +1,69 @@
---
title: 用Node+express搭建本地https服务
tags: []
id: '90'
categories:
- - 分享
date: 2017-01-24 15:21:05
---
1.安装node环境(自行谷歌百度,不赘述) 2.安装express(自行谷歌百度,不赘述) 3.打开命令行,利用openssl生成证书文件
```js
//生成私钥key文件
openssl genrsa 1024 > /keys/private.pem
//通过私钥文件生成CSR证书签名
openssl req -new -key /keys/private.pem -out /keys/csr.pem
//通过私钥文件和CSR证书签名生成证书文件
openssl x509 -req -days 365 -in /keys/csr.pem -signkey /keys/private.pem -out /keys/file.crt
```
4.编写server文件
```js
var app = require('express')();
var fs = require('fs');
var http = require('http');
var https = require('https');
//引入私钥、证书
var privateKey = fs.readFileSync('./keys/private.pem', 'utf8');
var certificate = fs.readFileSync('./keys/file.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
//创建服务,设置端口号
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
var PORT = 18080;
var SSLPORT = 18081;
//监听端口号
httpServer.listen(PORT, function() {
console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
httpsServer.listen(SSLPORT, function() {
console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});
//路由
app.get('/', function(req, res) {
if(req.protocol === 'https') {
res.status(200).send('这是一个经过加密的https请求!');
}
else {
res.status(200).send('这是一个普通的http请求!');
}
});
```
5.启动服务
```js
node server.js
```