Node.js中的HTTPS示例


 

  1. 需要openssl的支持, openssl本身不提供windows的安裝程序,可以按照如下的步驟進行安裝:

    (參考https://conetrix.com/Blog/how-to-install-openssl-on-windows-7,並復制到下面)

How-to Install OpenSSL on Windows 7

Download and run the Cygwin installer from their web site:www.cygwin.com.  OpenSSL is not one of that packages that gets installed by default with Cygwin.  The important part of install is choosing OpenSSL as one of the packages you install, because that package is not selected by default.  You do this by searching for "openssl" on the "Select Packages" step, expanding "Net" option, clicking on the "Skip" image so that a version shows, and clicking the "Next" button.  Use the image below as a reference. [more] 

 

安裝完后,在cygwin的bin目錄下就可以找到openssl.exe.

  1. 寫如下的node.js文件。

var https = require('https'),

pem = require('pem');

 

pem.config({

pathOpenSSL: 'C:\\cygwin64\\bin\\openssl.exe'

});

 

pem.createCertificate({days:1, selfSigned:true}, function(err, keys){

https.createServer({key: keys.serviceKey, cert: keys.certificate}, function(req, res){

res.end('o hai!')

}).listen(843);

});

 

如果是linux則不需要pem.config,由於windows下openssl所在的路徑不是node.js默認查找的路徑,所以需要pem.config.

其他情況下如果openssl的路徑不對,也需要pem.config.

如果找不到pem模塊,需要運行npm install pem 進行安裝。

 

  1. 運行該文件,然后訪問https://localhost:843,就可以看到o hi的結果了。

更多node.js SSL的配置見這里: https://nodejs.org/api/https.html

上面的例子用的是自己創建的證書,所以訪問的時候會有證書警告。

如果用的是公網可用的證書,則需要參考https://nodejs.org/api/https.html的例子。比如:

const https = require('https');

const fs = require('fs');

 

const options = {

key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),

cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')

};

 

https.createServer(options, (req, res) => {

res.writeHead(200);

res.end('hello world\n');

}).listen(8000);

 

或者

const https = require('https'); 

const fs = require('fs'); 

 

const options = { 

 pfx: fs.readFileSync('server.pfx') 

}; 

 

https.createServer(options, (req, res) => { 

 res.writeHead(200); 

 res.end('hello world\n'); 

}).listen(8000); 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM