简体   繁体   中英

How to properly assign development vs production variables?

I don't know how to ask this question, so I will describe what I'm doing, and I'd like some enlightenment.

I'm using node with express for server-side rendering.

When I'm developing the web app, there's a module holding a variable which is shared across all the express routes, instead of hard-coding it.

config.js

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

index.js route

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;

When it's time to deploy the app, I manually change the config.js into the server's IP address:

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

Another example is the scripts.js file referenced in the HTML head, which handles the DOM changes. Again, the server IP address is placed in the variable.

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());

What is a proper way to handle these variable changes automatically?

Is there a reason for fully qualifying the reference? If your directory structure is the same you could just use relative referencing, for example change '${ipAddress}/place-order' into '/place-order'

One proper way would be to use the processes environment. For example you could switch based on NODE_ENV :

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

For sure you could also take a custom variable

const ipAddress = process.env.ORDER_SERVER;

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


To pass the changes to clientside javascript you need to write them into the files delivered to the client somewhere on the server. That could be done easily with templates, eg ejs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM