How to get current domain address in sails.js

前端 未结 6 1454
再見小時候
再見小時候 2021-01-18 22:23

I trying to get current web address using sails.js.

I tried the following:

req.param(\'host\') and req.param(\'X-Forwarded-Protocol\') 
6条回答
  •  臣服心动
    2021-01-18 22:59

    Just to preface this answer: there is no reliable, cross-platform way to automatically detect the external URL of a running Sails app (or any other Node app). The getBaseUrl() method described below uses a combination of user-supplied and default configuration values to make a best guess at an app's URL. In mission-critical situations, you are advised to pre-determine the URL and save it in a custom environment-dependent configuration value (e.g. sails.config.appUrl) that you can reference elsewhere in the app.

    If you're on Sails >= v0.10.x, you can use sails.getBaseurl() to get the full protocol, domain and port that your app is being served from. Starting with Sails v0.10.0-rc6, this also checks the sails.config.proxyHost and sails.config.proxyPort, which you can set manually in your one of your config files (like config/local.js) if your app is being served via a proxy (e.g. if it's deployed on Modulus.io, or proxied through an Nginx server).

    Sails v0.9.x doesn't have sails.getBaseurl, but you can always try copying the code and implementing yourself, probably in a service:

    getBaseUrl

    function getBaseurl() {
      var usingSSL = sails.config.ssl && sails.config.ssl.key && sails.config.ssl.cert;
      var port = sails.config.proxyPort || sails.config.port;
      var localAppURL =
        (usingSSL ? 'https' : 'http') + '://' +
        (sails.getHost() || 'localhost') +
        (port == 80 || port == 443 ? '' : ':' + port);
    
      return localAppURL;
    };
    

    you'll notice this relies on sails.getHost(), which looks like:

    function getHost() {
      var hasExplicitHost = sails.config.hooks.http && sails.config.explicitHost;
      var host = sails.config.proxyHost || hasExplicitHost || sails.config.host;
      return host;
    };
    

提交回复
热议问题