How to enable https with koa
井民全, Jing, mqjing@gmail.com
1. Setup KOA for https
Step 1: Create certification file and key
Command
openssl req -nodes -new -x509 -keyout server.key -out server.cert
Result
Output
./server.cert: certification file
./server.key: key
Step 2: Write the server code
File: ./webserver.js
const http = require("http"); const https = require("https"); const fs = require("fs");
const serve = require('koa-static') const Koa = require('koa'); const path = require('path') const app = new Koa();
console.log('__dirname = ' + __dirname); app.use(serve(path.join(__dirname, '/public')))
http.createServer(app.callback()).listen(3000); console.log('http, listening on port 3000');
const options = { key: fs.readFileSync("./server.key", "utf8"), cert: fs.readFileSync("./server.cert", "utf8") }; https.createServer(options, app.callback()).listen(3001); console.log('https, listening on port 3001');
|
Result
2. The Root Page
vi ./public/index.html
3. Start the webserver
node webserver.js
Output
4. Verification
4.1. Test https
https://web-server-ip:3001
4.2. Test http
http//web-server-ip:3000
5. Reference
https://www.cnblogs.com/Wayou/p/koa_local_https.html