Sails.JS HTTP + HTTPS

后端 未结 8 2254
夕颜
夕颜 2021-01-02 04:49

I am trying to figure out how to lift a sails app that responds to both HTTP and HTTPS requests. I used the config/local.js method of configuring express like so (detailed h

8条回答
  •  梦毁少年i
    2021-01-02 05:36

    1-Uncomment the path to your SSL Certificates in your local.js or add path to your SSL Certificates in your config/env/production.js.

        module.exports  = {
     ssl: {
         ca: require('fs').readFileSync(__dirname + '/ssl/ca.crt'),
         key: require('fs').readFileSync(__dirname + '/ssl/key.key'),
         cert: require('fs').readFileSync(__dirname + '/ssl/cert.crt')
       },
     port: 443
    }
    

    2-Add a policies section in your config/env/production.js

        module.exports  = {
     ssl: {
         ca: require('fs').readFileSync(__dirname + '/ssl/ca.crt'),
         key: require('fs').readFileSync(__dirname + '/ssl/key.key'),
         cert: require('fs').readFileSync(__dirname + '/ssl/cert.crt')
       },
     port: 443,
     policies: {
        '*': 'isHTTPS'
       }
    }
    

    3-Create a isHTTPS.js policy in your api/policies folder. This policy will redirect the HTTP request to HTTPS

      module.exports = function(req, res, next) {
        if (req.secure) {
            // Already https; don't do anything special.
            next();
        } else {
            // Redirect to https.
            res.redirect('https://' + req.headers.host + req.url);
        }
    };
    

    4-Then we will edit the config/bootstrap.js file and listen to port 80 if the environment is production, so that we can redirect the requests to 443 i.e SSL

        var http = require( 'http' );
    module.exports.bootstrap = function(cb) {
        //If the environment is production, then listen on port 80 
        if(sails.config.environment === "production") {
            http.createServer( sails.hooks.http.app ).listen( 80 );        
        }
        cb();
    }
    

提交回复
热议问题