在nodejs中使用express能够快速搭建起web框架,但默认是http协议访问,这对于小绿锁爱好者的我固然是没法忍受的。毕竟https已经成为了主流。本篇文章会给你们介绍如何给express框架中的项目配置https服务,让用户能够经过浏览器使用https进行访问html
1.安装expressnode
npm install express -g
在安装了express以后,咱们就能够进行新项目的建立了,进入项目存放文件夹。执行:web
express -e ejs projectname
执行后可见工程目录下出现如下文件夹:express
cd [项目所在目录] && npm install
因为我使用的是阿里云的服务器,在此以前已经开放了443的监听安全组,没有配置安全组的小伙伴还须要手动配置一下npm
将SSL证书安装到项目文件夹中,好比放到新建的certificate文件夹。浏览器
完成以上步骤后,修改项目的启动文件,我这里的启动文件是app.js安全
下面是个人实现代码:服务器
const express=require("express"); const app=express(); app.use(express.static('public')) // app.get('/',function(req,res){ // res.redirect('./web/index.html'); // }); // app.listen(80,"内网ip"); var path = require('path'); var fs = require('fs'); //使用nodejs自带的http、https模块 var http = require('http'); var https = require('https'); //根据项目的路径导入生成的证书文件 var privateKey = fs.readFileSync(path.join(__dirname, './certificate/cert-1533745826203_www.dreamyheart.com.key'), 'utf8'); var certificate = fs.readFileSync(path.join(__dirname, './certificate/cert-1533745826203_www.dreamyheart.com.crt'), 'utf8'); var credentials = {key: privateKey, cert: certificate}; var httpServer = http.createServer(app); var httpsServer = https.createServer(credentials, app); //能够分别设置http、https的访问端口号 var PORT = 80; var SSLPORT = 443; //建立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,next) { res.redirect('./web/index.html'); }); app.get('*', function (req, res) { res.sendfile('./public/web/404.html'); });
执行node app.jsapp
部署https完毕框架