Use nodejs set up HTTPS server

Step 1: Create a project directory, npm init initialize the project, the installation express.

npm install express --save
Step: http.js new file, the original code is as follows.

var express = require(“express”);
var app = express();
var fs = require(‘fs’);

The third step: Use openssl to generate a self-signed certificate (free, local tests use), there are two steps:

Generate a Private Key and CSR.

openssl req -new -newkey rsa: 2048 -nodes -out mydomain.csr -keyout private.key
on the use of step-generated private.key and mydomain.csr generate a self-signed certificate.

openssl x509 -req -days 365 -in mydomain.csr -signkey private.key -out mydomain.crt
Step four: perfect http.js.

var express = require(“express”);
var app = express();
var fs = require(‘fs’);

var key = fs.readFileSync(‘private.key’);
var cert = fs.readFileSync(‘mydomain.crt’);

var options = {
key: key,
cert: cert
};
// Run static server
var https = require(‘https’);
https.createServer(options, app).listen(8888);

This basically you're done, write a index.html in the project directory, the last run in the project directory:

node http.js
finally open the browser, the address bar enter https: // localhost: 8888 after the browser displays your connection is not secure
clicks advance, directly proceed on the line (chrome).
If you click on the address bar exclamation mark, you can pop-up box, you can view the certificate, as follows:

SSL certificate
stole the lazy, direct use of the web performance in action code book to the first section into a
https connection. There is need to look code on git.

Reference:
https://medium.com/@nileshsin...
https://www.akadia.com/servic...

Original articles published 0 · won praise 0 · Views 14

Guess you like

Origin blog.csdn.net/gongjian999/article/details/103986732