Nodejs Https Server Notes

环境准备

  • nodejs:v10.16.0
  • npm:6.9.0

生成证书

1
2
3
4
5
6
keytool -genkeypair -alias vsd -validity 7200 -keyalg RSA -keysize 4096 -storetype JKS -keystore vsd.keystore -storepass vsd@2019 -keypass vsd@2019 -dname "CN=v.s.d, OU=dtts, O=dtts"

keytool -v -importkeystore -srckeystore vsd.keystore -srcalias vsd -srcstorepass vsd@2019 -srckeypass vsd@2019 -destkeystore vsd.p12 -deststoretype PKCS12 -deststorepass vsd@2019 -destkeypass vsd@2019

openssl pkcs12 -in vsd.p12 -nocerts -nodes -out vsd.key.pem -passin pass:vsd@2019
openssl pkcs12 -in vsd.p12 -clcerts -nokeys -out vsd.cert.pem -passin pass:vsd@2019

安装依赖

1
npm install express https http fs body-parser

创建文件

vsd.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var bodyParser = require('body-parser');

// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('qmsauthn.key.pem'),
cert: fs.readFileSync('qmsauthn.cert.pem')
};

// Create a service (the app object is just a callback).
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
// in latest body-parser use like below.
app.use(bodyParser.urlencoded({ extended: true }));

// get api
app.get('/api/v1', (req, res) => {
res.status(200).send({
success: 'true',
message: 'todos retrieved successfully',
})
});

// post api (Content-Type: application/x-www-form-urlencoded)
app.post('/api/v2', (req, res) => {
console.log(req.body);
res.status(200).send({
success: 'true',
message: 'todos retrieved successfully',
})
});

// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);

访问

http

1
curl -i http://v.s.d/api/v1
1
2
3
4
curl -X POST \
http://v.s.d/api/v2 \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d aa=111