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?
For 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.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
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')
. 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.
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.