[英]Hard-coded URL's
I have a query regarding hard-coded url's. 我有一个关于硬编码网址的查询。 When making a post call from JavaScript using jquery I do it as $.post('http://localhost:8000/timer/check/'
使用jquery从JavaScript进行发布时,我将其设置为$.post('http://localhost:8000/timer/check/'
Now this works fine on my development server. 现在,这在我的开发服务器上可以正常工作。 When I have to deploy it on another server I have to manually change all the url's in the code. 当我必须将其部署在另一台服务器上时,我必须手动更改代码中的所有url。 So how does one avoid hard-coding url's? 那么如何避免对URL进行硬编码?
For achieve this you have to use write below tag in your meta tag 为了实现这一点,您必须在meta标记中使用以下标记
<head>
<base href="{{your base url_here}}">
</head>
After this you have to write path relative to this base url. 之后,您必须编写相对于该基本URL的路径。
For Example 例如
<head>
<base href="http://localhost:8000/timer/check/">
</head>
If full URL is http://localhost:8000/timer/check/test.php
. 如果完整的URL是http://localhost:8000/timer/check/test.php
。 Now you can write relative to base url 'test.php'
in ajax call. 现在,您可以在ajax调用中相对于基本URL 'test.php'
编写代码。
Example: https://jsfiddle.net/ptLzs7m5/1/ 示例: https : //jsfiddle.net/ptLzs7m5/1/
try like this 这样尝试
var host = window.location.hostname;
var url = host + "/" + timer/check/;
Now you can pass the url to your post method 现在,您可以将网址传递给post方法
you can use this also 你也可以用这个
window.location.protocol //you'll get your protocol `http` or `https`
window.location.port //this will return the port
There are some solutions to this common problem - 有一些解决此常见问题的方法-
1) Use $.post('./timer/check')
. 1)使用$.post('./timer/check')
。 This will take the current domain and append the url (RECOMMENDED) 这将采用当前域并附加网址(推荐)
2) Create a global variable and use it wherever you want. 2)创建一个全局变量,并在任何需要的地方使用它。 Assign local url when working on dev and assign prod url when working on production. 在开发人员工作时分配本地URL,在生产工作时分配生产URL。
3) Create a wrapper and always use that wrapper to send the request. 3)创建一个包装器,并始终使用该包装器发送请求。 Create a global variable with your current status(Dev or Prod) as it's value and keep changing it. 创建一个具有当前状态(Dev或Prod)作为其值的全局变量,并不断对其进行更改。 And use it Like this- 并像这样使用它-
post(url) {
var baseurl = '';
if(CURRENT_ENVIRONMENT=='DEV')
baseurl = 'http://localhost:8080';
else if(CURRENT_ENVIRONMENT=='PROD')
baseurl = 'http://yourwebsiteurl';'
$.post(baseurl+'/timer/check')
//and so on
}
You can use whichever you prefer. 您可以使用自己喜欢的任何一种。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.