如何启用我所有的路由都具有https并将HTTP强制为https?

时间:2018-08-18 19:46:56

标签: javascript node.js express

我不明白如何强制所有路由都具有https,并且始终将http强制为https。谁能建议我如何更改下面的代码?我对node.js仍然是新手。任何帮助将不胜感激。

index.js

const express = require('express');
const hbs = require('hbs');
const path = require('path');
var morgan = require('morgan')
var session = require('express-session')
const MongoStore = require('connect-mongo')(session);
var passport = require('passport')
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/sth');

const mainMiddleware = require('./middleware/main.js');
const port = process.env.PORT || 3000;
var app = express();
app.use(morgan('dev'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded

app.use(session({
    secret: 'alsjbfkajsbef09876', //salt
    resave: false, // always re-init cookie
    saveUninitialized: false, // always create session even if not log in
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}))
app.use(passport.initialize());
app.use(passport.session());

app.use('/public', express.static(path.join(__dirname,'public')));

app.set('view engine', 'hbs');

app.use(mainMiddleware);

app.get('/', function (req, res) {
    let loginStatus = req.isAuthenticated() ? "DASHBOARD" : ""
    let dashboard = req.isAuthenticated() ? "/client/current" : "/"
    res.render('frame.hbs', {content: 'homeContent', css: 'home.css', dashboard, loginStatus, script: ['online-tracking.js']})
})

//----include routes
app.use('/api', require('./routes/api'));
app.use('/', require('./routes/page'));
app.use('/client', require('./routes/client-page'));
app.use('/admin', require('./routes/admin-page'));


//----connecting to port
app.listen(port,()=>{
    console.log(`success connection to port ${port}`);
})

3 个答案:

答案 0 :(得分:1)

通过greenlock-express(在NPM上可用),这非常容易,并且还可以通过LetsEncrypt的SSL证书与您联系。这是文档中的示例脚本。 https://git.coolaj86.com/coolaj86/greenlock-express.js

'use strict';

require('greenlock-express').create({

  // Let's Encrypt v2 is ACME draft 11
  version: 'draft-11'

  // Note: If at first you don't succeed, switch to staging to debug
  // https://acme-staging-v02.api.letsencrypt.org/directory
, server: 'https://acme-v02.api.letsencrypt.org/directory'

  // Where the certs will be saved, MUST have write access
, configDir: '~/.config/acme/'

  // You MUST change this to a valid email address
, email: 'john.doe@example.com'

  // You MUST change these to valid domains
  // NOTE: all domains will validated and listed on the certificate
, approveDomains: [ 'example.com', 'www.example.com' ]

  // You MUST NOT build clients that accept the ToS without asking the user
, agreeTos: true

, app: require('express')().use('/', function (req, res) {
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    res.end('Hello, World!\n\n .js');
  })

  // Join the community to get notified of important updates
, communityMember: true

  // Contribute telemetry data to the project
, telemetry: true

//, debug: true

}).listen(80, 443);

自从我尝试过-这是我构建的每个节点/快速站点的基础。

在找到这个之前,我实际上会使用Apache作为node的前端代理。如果您希望将站点绑定到虚拟主机环境中的port:443,则无论如何您仍然会觉得这是更好的选择。

我对greenlock的真正喜欢是,您将init脚本中的port:80和port:443绑定在一起,并且还为您处理重定向。

答案 1 :(得分:0)

如果要使用https加密连接,则需要SSL证书进行验证,以证明您是对内容的真正保证。大多数托管服务(例如Microsoft Azure和Amazon Web Services)都可以创建SSL证书

答案 2 :(得分:0)

尝试将此代码包含在Express项目中

var http = require('http');
var https = require('https');
app.set('port', port);
app.set('secPort', port + 443);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
var options = {
    key: fs.readFileSync('/private.key'),
    cert: fs.readFileSync('/certificate.pem')
 };
var secureServer = https.createServer(options, app);
secureServer.listen(app.get('secPort'), () => {
    console.log('server listening on port', app.get('secPort'));
});
secureServer.on('error', onError);
secureServer.on('listening', onListening);
app.all('*', (req, res, next) => {
    if (req.secure) {
        return next();
    } else {
        res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url);
    }
});