简体   繁体   English

在不同的环境中更改URL?

[英]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)? 在环境中(本地,开发,测试,登台和生产)移动JavaScript时,更改与之通信的URL的最佳方法是什么? So say you have a backend url that you communicate with will change in different environments: 假设您有一个要与之通信的后端URL,它将在不同的环境中发生变化:

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. 我想到也许使用grunt / gulp脚本来修改url,但是不确定这是否是最好/建议的方法。 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. 我敢肯定,有些人会说不要更改URL结构,并且您不必担心它,但是不幸的是,URL现在有点混乱,直到我们重新构造这一切为止。 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. 过去,我们在Visual Studio中使用了post build步骤来对CSS进行版本控制,但这是一个很棘手的解决方案。

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. 它应该位于.config中,从.config中读取它,并通过隐藏的控件呈现到页面/视图,或者动态生成JavaScript变量并追加到页面/视图。 Before posting the request to api, JavaScript code can access the hidden control or dynamically generate variable. 在将请求发布到api之前,JavaScript代码可以访问隐藏的控件或动态生成变量。

This is what you want, https://msdn.microsoft.com/en-us/library/dd465326(v=vs.110).aspx . 这就是您想要的https://msdn.microsoft.com/zh-cn/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. 您将必须为每个环境添加配置文件( https://msdn.microsoft.com/en-us/library/kwybya3w.aspx ),然后使用第一个链接中描述的转换来生成正确的配置文件,具体取决于在环境上。

Then in your code you can just get the URL from the config file and set it to a javascript variable. 然后,在您的代码中,您只需从配置文件中获取URL并将其设置为javascript变量即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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