nodejs的express框架建立https服務器

一 openssl建立https私鑰和證書html

1.下載windows版openssl:node

http://slproweb.com/products/Win32OpenSSL.htmlweb

Win64OpenSSL_Light-1_1_1b.exeexpress

2.安裝並使用openssl:npm

2.1 正常安裝openssl.exewindows

2.2 進入openssl安裝目錄的bin裏面瀏覽器

#生成私鑰key文件服務器

openssl genrsa 1024 > ./private.pem app

#經過私鑰文件生成CSR證書籤名 框架

openssl req -new -key ./private.pem -out csr.pem

#經過私鑰文件和CSR證書籤名生成證書文件

openssl x509 -req -days 365 -in csr.pem -signkey ./private.pem -out ./file.crt

 

二 windows下安裝和使用express框架:

1.全局安裝express框架,cmd打開命令行,輸入以下命令:

        npm install -g express

   express 4.x版本中將命令工具分出來,安裝一個命令工具,執行命令:

        npm install -g express-generator

     輸入express --version驗證

2.若是在執行js文件仍報Error: Cannot find module express錯誤。

解決辦法:
    在本身的工程目錄下再次執行:
        npm install express

三 建立https服務器

1.進入node項目下,拷貝私鑰和證書到此目錄下

2.建立node服務程序https.js:

var app = require('express')();
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('./private.pem', 'utf8');
var certificate = fs.readFileSync('./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);
});

// Welcome
app.get('/', function(req, res) {
    if(req.protocol === 'https') {
        res.status(200).send('Welcome to Safety Land!');
    }
    else {
        res.status(200).send('Welcome!');
    }
});

3.運行:node https.js

4.瀏覽器訪問:https://localhost:18081/

 

參考:
https://blog.csdn.net/gengxiaoming7/article/details/78505107

https://www.cnblogs.com/handongyu/p/6260209.html

https://blog.csdn.net/mlsama/article/details/8021103

相關文章
相關標籤/搜索