1. 程式人生 > >基於Node.js Express搭建Https伺服器

基於Node.js Express搭建Https伺服器

內容

1、安裝Node.js

2、安裝Expressexpress-generator

3、利用express-generator生成新專案

4、生成SSL證書

5、將專案從http轉換為https

關鍵詞:Node.jsExpressHttpsEJSSSL證書

                                                        1、安裝Node.js(自帶npm

1.1 下載Node.jsWindows Installer.msi, 32/64位)

    https://nodejs.org/en/download/

1.2 雙擊msi檔案進行安裝

    預設所有選項

1.3 測試

    在鍵盤按下【win+R】鍵,輸入cmd,然後回車,開啟cmd視窗

    node -v:顯式版本號,說明node.js安裝成功了

    npm -v:顯式版本號,說明自帶的npm安裝成功了

        npmNode.js依賴的包進行管理——安裝/解除安裝Node.js需要裝的東西

1.4 環境配置【這一步可不做

    當執行:npm install *** [-g]-g代表全域性安裝)命令時,如果不配置,模組安裝到C:\Users\使用者名稱\AppData\Roaming\npm中,佔C盤空間。要想將全域性模組快取放在指定資料夾,需配置npm全域性模組快取cache

路徑。

    npm config set prefix "D:\Develop\nodejs\node_global"

    npm config set cache "D:\Develop\nodejs\node_cache"

    還要設定環境變數:

    (1)新建系統變數NODE_PATH=D:\Develop\nodejs\node_global\node_modules

    (2)將使用者變數Path中的C:\Users\使用者名稱\AppData\Roaming\npm修改為D:\Develop\nodejs\node_global

    配置完後,安裝一個module測試:如npm install express -g。此時express會被

安裝到D:\Develop\nodejs\node_global。

    說明:通過npm安裝模組時都是去國外的映象下載的,有的時候由於網路原因會導致安裝模組失敗,好在阿里有團隊維護國內映象:http://npm.taobao.org/ 上面有使用說明

                                                        2、安裝expressexpress-generator

2.1 安裝express(全域性安裝)

npm install express -g

2.2 安裝express-generator(全域性安裝)

npm install express-generator -g

                                                                 3、生成新express專案

3.1 進入cmd視窗,cd到新專案的“父目錄”

3.2 執行如下命令

express --view ejs project1 project1:專案名)

--view <engine>新增檢視引擎,支援:dust|ejs|hbs|hjs|jade|pug|twig|vash,預設是jade

這裡選用了ejs

Cmd視窗輸出結果:

D:\workspace\web\express>express --view ejs project1

   create : project1

   create : project1/package.json

   create : project1/app.js

   create : project1/public

   create : project1/routes

   create : project1/routes/index.js

   create : project1/routes/users.js

   create : project1/views

   create : project1/views/index.ejs

   create : project1/views/error.ejs

   create : project1/bin

   create : project1/bin/www

   create : project1/public/javascripts

   create : project1/public/stylesheets

   create : project1/public/stylesheets/style.css

   create : project1/public/images

   install dependencies:

     > cd project1 && npm install

   run the app:

     > SET DEBUG=project1:* & npm start

3.3 安裝依賴項

上述project1/package.json檔案內容如下:

{

  "name": "project1",

  "version": "0.0.0",

  "private": true,

  "scripts": {

    "start": "node ./bin/www"

  },

  "dependencies": {

    "body-parser": "~1.18.2",

    "cookie-parser": "~1.4.3",

    "debug": "~2.6.9",

    "ejs": "~2.5.7",

    "express": "~4.15.5",

    "morgan": "~1.9.0",

    "serve-favicon": "~2.4.5"

  }

}

Dependencies中列出了依賴項,執行如下命令安裝:cd project1 && npm install

Cmd視窗輸出結果:

D:\workspace\web\express>cd project1 && npm install

npm notice created a lockfile as package-lock.json. You should commit this file.

added 58 packages in ***s

說明:這些modules安裝到了\project1\node_modules目錄下(本地)。

3.4 測試,在cmd視窗執行以下命令

SET DEBUG=project1:* & npm start

也可以直接執行npm start(不好除錯資訊)

cmd視窗輸出結果:

D:\workspace\web\express\project1>SET DEBUG=project1:* & npm start

> [email protected] start D:\workspace\web\express\project1

> node ./bin/www

  project1:server Listening on port 3000 +0ms

Express

Welcome to Express

respond with a resource

3.5 專案project1內容說明

/bin:用來啟動應用(伺服器)

    node ./bin/www

      建立http伺服器(與express app關聯);啟動http伺服器(偵聽3000

app.js程式:main檔案,這個是伺服器啟動的入口

      建立express app

    設定檢視引擎(view engine)、檢視檔案路徑

      指定”/”和”/users”的路由模組

/public: 存放靜態資源目錄

/routes:路由用於確定應用程式如何響應對特定端點的客戶機請求,

    index.js - 響應”/”的響應(在app.js中指定)

    users.js - 響應”/users”的響應(在app.js中指定)

/views: 模板檔案所在目錄,檔案格式為.ejs

    Index.ejs - 一個簡單的網頁,有變數title

    Error.ejs - 顯式錯誤資訊

3.6 project1執行過程說明

1npm start

訪問package.jason,裡面有"start": "node ./bin/www"

所以實際執行的是node ./bin/www

2www

建立http伺服器(與express app關聯)

啟動http伺服器(偵聽3000

3app.js中指定了”/”和”/users”Router

           也指定了檢視所在目錄./views,所用檢視引擎是ejs

4)訪問網頁http://localhost:3000

    路由到./routers/index.js中的router.get(”/”,...)

    繪製網頁index.ejs:(檢視目錄是./views,變數title=’Express’)

             res.render('index', { title: 'Express' });

5)訪問網頁http://localhost:3000/users

    路由到./routers/users.js中的router.get(”/”,...)

    返回字串:res.send('respond with a resource');

                                                      3、生成SSL證書

上述project1提供的是HTTP伺服器,很多情況下需要HTTPS伺服器。為此,首先要得到SSL證書。這裡介紹如何在Windows下生成自簽名證書。

3.1 下載openssl-0.9.8k_WIN32.zip,並解壓

3.2 進入cmd視窗,cd到解壓後的bin目錄中

3.3 openssl.exe,進入OPENSSL執行介面

3.4 生成一個RSA私鑰

    命令列:genrsa -des3 -out server.key 2048

        des3演算法,2048位強度,server.key是祕鑰檔名

     注意:此時需要提供一個至少4位的密碼(如abcd)。

3.5 生成CSR(證書籤名請求)——自簽名(內部或測試需求)

    命令列:req -new -key server.key -out server.csr

    說明:需輸入國家、地區、城市、組織、組織單位、Common NameEmail

    其中Common Name以寫自己的名字或域名。要支援httpsCommon Name應與域 名保持一致,否則會引起瀏覽器警告。(這裡我隨便填的,湊合能用

    樣例:國家:CN、省州:Beijing、城市:Beijing

          組織名稱:joyios、組織單位名稱:IT

                Common Namedemo.joyios.com、電郵:[email protected]

3.6 刪除私鑰中的密碼

建立私鑰指定密碼後,每次Apache啟動Web伺服器時,都會要求輸入密碼。

要刪除私鑰中的密碼,操作如下:rsa -in server.key -out server_no_passwd.key

此時需要輸入建立私鑰時輸入的密碼

3.7 生成自簽名證書

說明:使用自簽名臨時證書時,瀏覽器會提示證書的頒發機構是未知的。

命令:x509 -req -days 365 -in server.csr -signkey server_no_passwd.key -out server.crt

server.crt就是SSL證書。

                                             4、將Http伺服器修改為https伺服器

4.1 SSL證書檔案拷貝到project1/bin目錄下(其它目錄也可)

    server_no_passwd.key

    server.crt

4.2 修改bin/www檔案,將http改為https

1)刪除var http = require('http'); 

    新增var https = require('https');

    新增var fs = require('fs');

2)讀入金鑰和證書檔案

    var privatekey = fs.readFileSync('bin/server_no_passwd.key', 'utf8');

    var certificate = fs.readFileSync('bin/server.crt', 'utf8');

3)構造https伺服器選項

    var options={key:privatekey, cert:certificate};

4)建立HTTPS伺服器

    var server = https.createServer(options, app);

    //var server = http.createServer(app);

(5)可以修改port為不同的埠

(6)偵聽時可給出回撥函式

    server.listen(port,function () { console.log('Https server listening on port ' + port); });

4.3 測試

1)執行npm start

2)訪問https://localhost:3000/

3)訪問https://localhost:3000/users