3.Node搭建https服務(wù)器
3.1配置express項目
$ cd /Users/51testing/Desktop/https
$ express HttpsService
.... ???install dependencies:
$ cd HttpsService && npm install ????run the app:
$ DEBUG=httpsservice:* npm start
$ cd HttpsService && npm install .....
執(zhí)行完畢后的目錄如下:
3.2配置文件
創(chuàng)建目錄certificate,將創(chuàng)建的文件拖入進去,
3.3編寫代碼
express默認(rèn)采用http協(xié)議,在bin/www目錄下配置入口文件;
我們在app.js文件中配置https服務(wù)器,nodejs默認(rèn)存在http與https模塊,直接引用即可.
#app.js中加入如下代碼:
varapp = express();//使用nodejs自帶的http、https模塊
varhttps =require('https');
varhttp =require('http');
varfs =require('fs');
//根據(jù)項目的路徑導(dǎo)入生成的證書文件
varprivateKey ?= fs.readFileSync(path.join(__dirname,'./certificate/private.pem'),'utf8');
varcertificate = fs.readFileSync(path.join(__dirname,'./certificate/ca.cer'),'utf8');
varcredentials = {key: privateKey, cert: certificate};
//創(chuàng)建http與HTTPS服務(wù)器
varhttpServer = http.createServer(app);
varhttpsServer = https.createServer(credentials, app);
//可以分別設(shè)置http壶辜、https的訪問端口號
varPORT =8000;
varSSLPORT =8001;
//創(chuàng)建http服務(wù)器
httpServer.listen(PORT,function(){
console.log('HTTP Server is running on: http://localhost:%s', PORT); });
//創(chuàng)建https服務(wù)器
httpsServer.listen(SSLPORT,function(){
console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT); });//可以根據(jù)請求判斷是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驗證
啟動服務(wù):
$ node bin/www
HTTP Serverisrunningon:http://localhost:8000
HTTPS Serverisrunningon: https://localhost:8001
**打開瀏覽器訪問:https://localhost:8001
**點擊繼續(xù)-高級--訪問不安全鏈接:
**訪問http服務(wù)器:http://localhost:8000