提前說明以下,我使用的電腦是mac
實現https水评,需要有證書。在mac下媚送,你可以進行如下操作中燥。
首先,打開終端塘偎,創(chuàng)建一個文件夾
mkdir certificate
進入該文件夾
cd certificate
然后輸入openssl (mac下openssl是系統自帶的疗涉,可以直接在終端使用拿霉。windows 電腦需要另行下載)
openssl
下面需要依次生成三個文件
-
首先是私鑰
genrsa -out private.pem 2048
-
生成證書簽名
req -new -key private.pem -out csr.pem
生成證書簽名需要填寫一些信息,依次按照提示填寫就行咱扣。以下是我隨便填寫的信息:
Country Name (2 letter code) [AU]:CH State or Province Name (full name) [Some-State]:CH Locality Name (eg, city) []:CH Organization Name (eg, company) [Internet Widgits Pty Ltd]:CH Organizational Unit Name (eg, section) []:CH Common Name (e.g. server FQDN or YOUR name) []:CH Email Address []:CH Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:123123123 An optional company name []:CH
-
最后一步绽淘,生成證書文件
x509 -req -in csr.pem -signkey private.pem -out csr.crt
完成,此時certificate文件夾中就存在三個文件csr.crt,csr.pem,private.pem闹伪。將這三個文件沪铭,放入node項目的根目錄。
現在要寫node項目的啟動js文件偏瓤,index.js
let express = require('express');
let app = express();
let fs = require('fs');
let https = require('https');
let http = require('http');
let privateKey = fs.readFileSync('private.pem', 'utf8');
let certificate = fs.readFileSync('csr.crt', 'utf8');
let cert = {key: privateKey, cert: certificate};
let httpServer = http.createServer(app);
let httpsServer = https.createServer(cert, app);
app.get('/', function(req, res) {
if(req.protocol === 'https') {
res.send('https require');
} else {
res.send('http require');
}
});
httpServer.listen(3000, function() {
console.log('HTTP Server is running');
});
httpsServer.listen(3001, function() {
console.log('HTTPS Server is running');
});
啟動node 服務器
node index.js
此時控制臺顯示
HTTP Server is running
HTTPS Server is running
然后去瀏覽器輸入 https://localhost:3001/
此時瀏覽器會攔截你訪問杀怠,因為生成的證書是無效的。不過你可以按繼續(xù)訪問(safari瀏覽器)或者高級選項繼續(xù)訪問(chrome瀏覽器)厅克。
如果你有自己的域名赔退,你看去網上申請免費試用的證書。舉個網站 https://www.startssl.com