node + express 实现https

来源:互联网 发布:linux if语句使用方法 编辑:程序博客网 时间:2024/05/29 15:40

生成证书

#生成私钥key文件
openssl genrsa 1024 > /path/to/private.pem
//
#通过私钥文件生成CSR证书签名
openssl req -new -key /path/to/private.pem -out csr.pem
//
#通过私钥文件和CSR证书签名生成证书文件
openssl x509 -req -days 365 -in csr.pem -signkey /path/to/private.pem -out /path/to/file.crt

本代码用express cli生成 , 更改里面的app.js

var express = require('express');var path = require('path');var favicon = require('serve-favicon');var logger = require('morgan');var cookieParser = require('cookie-parser');var bodyParser = require('body-parser');var index = require('./routes/index');var smallApp = require('./routes/smallApp');var users = require('./routes/users'); var app = express();// view engine setupapp.set('views', path.join(__dirname, 'views'));app.set('view engine', 'ejs');var fs = require('fs');var http = require('http');var https = require('https');var privateKey  = fs.readFileSync('../public/path/to/private.pem', 'utf8');var certificate = fs.readFileSync('../public/path/to/file.crt', 'utf8');var credentials = {key: privateKey, cert: certificate};var httpServer = http.createServer(app);var httpsServer = https.createServer(credentials, app);var PORT = 80;var SSLPORT = 443;// httpServer.listen(PORT, '172.17.53.173' ,function() {//     console.log('HTTP Server is running on: http://localhost:%s', PORT);// });httpsServer.listen(SSLPORT, '172.17.53.173' , function() {    console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);});// uncomment after placing your favicon in /public//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));app.use(logger('dev'));app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));app.use(cookieParser());app.use(express.static(path.join(__dirname, 'public')));app.use('/', smallApp );app.use('/users', users);// catch 404 and forward to error handlerapp.use(function(req, res, next) {  var err = new Error('Not Found');  err.status = 404;  next(err);});// error handlerapp.use(function(err, req, res, next) {  // set locals, only providing error in development  res.locals.message = err.message;  res.locals.error = req.app.get('env') === 'development' ? err : {};  // render the error page  res.status(err.status || 500);  res.render('error');});module.exports = app;

smallApp.js

var express = require('express');var router = express.Router();/* GET home page. */router.get('/', function(req, res, next) {  if( req.protocol == "https" ){    res.render('smallApp/index' ,{ protocol : 'https'} );  }else if( req.protocol == "http" ){    res.render('smallApp/index' ,{ protocol : 'http'} );  }});module.exports = router;

这里写图片描述

这里写图片描述