【问题标题】:How to properly assign development vs production variables?如何正确分配开发变量和生产变量?
【发布时间】:2018-05-23 15:12:15
【问题描述】:

我不知道如何问这个问题,所以我将描述我在做什么,我希望得到一些启发。

我正在使用 nodeexpress 进行服务器端渲染。

当我开发网络应用程序时,有一个模块包含一个变量,该变量在所有快速路由之间共享,而不是硬编码。

config.js

module.exports = {
    ipAddress: "http://localhost:8080"
}

index.js 路由

var config = require("../../config.js");

router
    .get('/', function (req, res) {
        var html = `
            <div class="content">
                <a href="${config.ipAddress}/orders">Orders</a>
                <a href="${config.ipAddress}/invoices">Invoices</a>
            </div>
        `
        res.send(html);
    });

module.exports = router;

部署应用时,我手动config.js更改为服务器的IP地址:

module.exports = {
    ipAddress: "http://255.255.255.255"
}

另一个例子是 HTML 头部中引用的 scripts.js 文件,它处理 DOM 的更改。同样,服务器 IP 地址被放置在变量中。

scripts.js

var ipAddress = "http://localhost:8080"; // To be changed into "http://255.255.255.255"

function placeOrder() {
    fetch(`${ipAddress}/place-order`, {
        method: "POST",
        headers: {
            "Accept": "application/json",
            "Content-type": "application/json"
        }
    })
    .then((res) => res.json())
    .then((data) => xonsole.log(data))
    .catch((err) => console.log(err));
}

document.getElementById("submit-order").addEventListener("click", () => placeOrder());

自动处理这些变量更改的正确方法是什么?

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

是否有理由完全限定参考?如果您的目录结构相同,您可以只使用相对引用,例如将 '${ipAddress}/place-order' 更改为 '/place-order'

【讨论】:

    【解决方案2】:

    一种正确的方法是使用流程环境。例如你可以基于NODE_ENV进行切换:

     const ipAdress = process.env.NODE_ENV === "production" ? "http://255.255.255" : "http://localhost";
    

    当然你也可以使用自定义变量

    const ipAddress = process.env.ORDER_SERVER;
    

    These variables can then be set to different values on different servers.


    要将更改传递给客户端javascript,您需要将它们写入传递给服务器某处客户端的文件中。这可以通过模板轻松完成,例如ejs。

    【讨论】:

    • 感谢您的回复。第二部分,即 HTML 头部中的scripts.js 怎么样?这对不属于 Node 的文件也有效吗?
    • @babevski 您必须将其写入客户端文件。
    • 我很抱歉没有将您的答案标记为正确。您正确回答了我的问题,但另一个问题一开始就告诉我不需要。
    • @babevski 是的,在这种情况下,另一个答案肯定是更好的解决方案...您不知道相对 URL? °_°
    • 是的,我很惭愧...我不知道我怎么从来没有意识到这一点。
    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 2020-04-20
    • 2017-04-16
    • 1970-01-01
    • 2017-04-23
    • 2019-11-03
    • 1970-01-01
    • 2014-09-10
    相关资源
    最近更新 更多