admin管理员组文章数量:1336632
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/'
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. So how does one avoid hard-coding 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/'
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. So how does one avoid hard-coding url's?
Share Improve this question asked Sep 8, 2016 at 7:48 Aniruddha BhondweAniruddha Bhondwe 83112 silver badges18 bronze badges 2-
9
Make the URLs relative to the root of the domain, eg
'/timer/check/'
– Rory McCrossan Commented Sep 8, 2016 at 7:48 - 1 You can do 2 things. 1) make relative urls 2)make a global variable with one hard coded url for your domain and then append it to individual urls, and on production or test change only one variable. – VJI Commented Sep 8, 2016 at 7:50
3 Answers
Reset to default 3For achieve this you have to use write below tag in your meta tag
<head>
<base href="{{your base url_here}}">
</head>
After this you have to write path relative to this base url.
For Example
<head>
<base href="http://localhost:8000/timer/check/">
</head>
If full URL is http://localhost:8000/timer/check/test.php
. Now you can write relative to base url 'test.php'
in ajax call.
Example: https://jsfiddle/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
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 mon problem -
1) Use $.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. Assign local url when working on dev and assign prod url when working on production.
3) Create a wrapper and always use that wrapper to send the request. Create a global variable with your current status(Dev or Prod) as it's value and keep changing it. 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.
本文标签: javascriptHardcoded URL39sStack Overflow
版权声明:本文标题:javascript - Hard-coded URL's - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742413920a2470340.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论