nodejs开发给express配置https服务器

在nodejs中使用express可以快速搭建起web框架,但默认是http协议访问,这对于小绿锁爱好者的我当然是无法忍受的。毕竟https已经成为了主流。本篇文章会给大家介绍如何给express框架中的项目配置https服务,让用户可以通过浏览器使用https进行访问

 

一、安装express(已安装node环境)

1.安装express

npm install express -g

 

二、生成新express项目

在安装了express之后,我们就可以进行新项目的创建了,进入项目存放文件夹。执行:

express -e ejs projectname

执行后可见工程目录下出现以下文件夹:

cd [项目所在目录] && npm install

 

三、配置证书

由于我使用的是阿里云的服务器,在此之前已经开放了443的监听安全组,没有配置安全组的小伙伴还需要手动配置一下

将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.js

部署https完毕

posted @ 2019-02-13 09:06  梦i  阅读(748)  评论(0编辑  收藏  举报