Enabling HTTPS on express.js

前端 未结 7 910
栀梦
栀梦 2020-11-22 08:44

I\'m trying to get HTTPS working on express.js for node, and I can\'t figure it out.

This is my app.js code.

var express = require(\'exp         


        
相关标签:
7条回答
  • 2020-11-22 09:40

    This is how its working for me. The redirection used will redirect all the normal http as well.

    const express = require('express');
    const bodyParser = require('body-parser');
    const path = require('path');
    const http = require('http');
    const app = express();
    var request = require('request');
    //For https
    const https = require('https');
    var fs = require('fs');
    var options = {
      key: fs.readFileSync('certificates/private.key'),
      cert: fs.readFileSync('certificates/certificate.crt'),
      ca: fs.readFileSync('certificates/ca_bundle.crt')
    };
    
    // API file for interacting with MongoDB
    const api = require('./server/routes/api');
    
    // Parsers
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    
    // Angular DIST output folder
    app.use(express.static(path.join(__dirname, 'dist')));
    
    // API location
    app.use('/api', api);
    
    // Send all other requests to the Angular app
    app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, 'dist/index.html'));
    });
    app.use(function(req,resp,next){
      if (req.headers['x-forwarded-proto'] == 'http') {
          return resp.redirect(301, 'https://' + req.headers.host + '/');
      } else {
          return next();
      }
    });
    
    
    http.createServer(app).listen(80)
    https.createServer(options, app).listen(443);
    
    0 讨论(0)
提交回复
热议问题