如何在sails.js中获取当前域地址 [英] How to get current domain address in sails.js

查看:22
本文介绍了如何在sails.js中获取当前域地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 sails.js 获取当前网址.

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

我尝试了以下方法:

req.param('host') and req.param('X-Forwarded-Protocol') 

返回未定义.

req.headers.host

返回本地主机.但我的域不是本地主机.

returns localhost. but my domain is not localhost.

如何获得??

推荐答案

只是作为这个答案的序言:没有可靠的、跨平台的方法来自动检测正在运行的 Sails 应用程序(或任何其他 Node 应用程序)的外部 URL.下面描述的 getBaseUrl() 方法使用 用户提供的 和默认配置值的组合来对应用程序的 URL 做出最佳猜测.在关键任务情况下,建议您预先确定 URL 并将其保存在自定义 环境相关配置值(例如sails.config.appUrl),您可以在应用程序的其他地方引用.

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.

如果您使用 Sails >= v0.10.x,您可以使用 sails.getBaseurl() 来获取您的应用所使用的完整协议、域和端口.从 Sails v0.10.0-rc6 开始,这还会检查 sails.config.proxyHostsails.config.proxyPort,您可以在您的配置之一中手动设置文件(如 config/local.js),如果您的应用通过代理提供服务(例如,如果它部署在 Modulus.io 上,或通过 Nginx 服务器代理).

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 没有 sails.getBaseurl,但您可以随时尝试复制代码并自己实现,可能在 服务:

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;
};

你会注意到这依赖于 sails.getHost(),它看起来像:

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;
};

这篇关于如何在sails.js中获取当前域地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆