1. 程式人生 > >Nodejs 搭建https伺服器(二)

Nodejs 搭建https伺服器(二)

$ cd /Users/51testing/Desktop/https  

$ express HttpsService

....    install dependencies:     

 $ cd HttpsService && npm install     run the app:     

 $ DEBUG=httpsservice:* npm start

 $ cd HttpsService && npm install .....

執行完畢後的目錄如下:


3.2 配置檔案

建立目錄certificate,將建立的檔案拖入進去,

 

3.3 編寫程式碼

express預設採用http協議,在bin/www目錄下配置入口檔案;我們在app.js檔案中配置https伺服器nodejs預設存在http與https模組,直接引用即可.

#app.js中加入如下程式碼:

var app = express();  //使用nodejs自帶的http、https模組

var https = require('https');

var http = require('http');

var fs = require('fs');  

//根據專案的路徑匯入生成的證書檔案

var privateKey  = fs.readFileSync(path.join(__dirname, 

'./certificate/private.pem'), 'utf8');

var certificate = fs.readFileSync(path.join(__dirname, './certificate/ca.cer'), 'utf8');

var credentials = {key: privateKey, cert: certificate};

//建立http與HTTPS伺服器

var httpServer = http.createServer(app);

var httpsServer = https.createServer(credentials, app);

//可以分別設定http、https的訪問埠號

var PORT = 8000;

var SSLPORT = 8001;  

//建立http伺服器

 httpServer.listen(PORT, function(){     

console.log('HTTP Server is running on: http://localhost:%s', PORT); });  

//建立https伺服器

 httpsServer.listen(SSLPORT, function(){     

console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT); });  //可以根據請求判斷是http還是https

app.get('/'function(req, res){     

if(req.protocol === 'https') {         

res.status(200).send('This is https visit!');     

}     else {        

 res.status(200).send('This is http visit!');    

 }

});

3.4 驗證

啟動服務:

$ node bin/www

 HTTPS Server is running on: https://localhost:8001

 

**點選繼續-高階--訪問不安全連結: