【问题标题】:How to get the node config in html file如何在html文件中获取节点配置
【发布时间】:2018-02-12 10:20:02
【问题描述】:

我根据环境有一个节点配置。 https://github.com/lorenwest/node-config

default.json

{
  "server": {
    "host": "localhost",
    "protocol": "http",
    "port": 9011
  }
}

我想在<script> 标签内的index.html 中得到这个。有谁知道这样做的方法是什么?

我可以在下面的 js 文件中获取此配置

app.js

var config = require('config');
console.log(config.server.host);

【问题讨论】:

  • 为什么需要这个?你想完成什么?
  • @FedericoklezCulloca 我在 index.html 中有另一个服务器的 url,到目前为止它是硬编码的。我希望它应该从配置文件中选择。它将请求从这台服务器发送到另一台服务器
  • 您可以添加一个服务器端渲染工具...您使用的是什么堆栈?
  • 我正在使用 nodejs ,表达框架。你说的“服务器端渲染工具”是什么意思?

标签: javascript node.js node-config


【解决方案1】:

我是node-config 的维护者。在一个复杂的应用程序中,您可能会有一些只希望在后端可见的秘密,以及一些您想与前端共享的值。

将您想与前端共享的所有值放在frontend 配置键下。

然后创建一个express 路由,在/config.jsfrontend 配置提供服务:

router.get('/config.js', _configjs);
// Cache the config, don't recompute it on every request
var configJavascript = 'window.CONFIG='+JSON.stringify(config.get('frontend'));
function _configjs (req, res) {
  res.setHeader("Content-Type", "text/javascript");
  // Last modified now
  res.setHeader('Last-Modified', (new Date()).toUTCString());
  // Cache the config for 5 minutes
  res.setHeader('Cache-Control', 'max-age='+(60*5));
  res.writeHead(200);
  res.end(configJavascript);
}

现在从前端加载/config.js后,您可以通过

【讨论】:

    【解决方案2】:

    对 app.js 文件进行 ajax 调用并获取配置文件数据并在 index.html 文件中使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 2014-12-18
      相关资源
      最近更新 更多