简体   繁体   中英

Change URL in different environments?

What is the best way to change a URL for javascript to communicate with as you move it through environments (local, dev, test, staging, & prod)? So say you have a backend url that you communicate with will change in different environments:

var request = new XMLHttpRequest();
request.open("POST", "/api/upload");

I thought of maybe using a grunt/gulp script to modify the url but not sure if this is the best/advised way to do it. I'm sure some of you will say don't change the URL structure and you won't have to worry about it but unfortunately are URLs are kind of a mess now and until we restructure everything this is what we have to live with. In the past we have used the post build step in visual studio to version our CSS but that's kind of a hacky solution.

It should be in .config, read it from .config and render to the page/view through a hidden control or dynamically generate a JavaScript variable and append to the page/view. Before posting the request to api, JavaScript code can access the hidden control or dynamically generate variable.

This is what you want, https://msdn.microsoft.com/en-us/library/dd465326(v=vs.110).aspx . You will have to add the profiles for each of your environment ( https://msdn.microsoft.com/en-us/library/kwybya3w.aspx ) and then use the transforms described in the first link to generate the right config files depending on the environment.

Then in your code you can just get the URL from the config file and set it to a javascript variable.

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