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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742413920a4439365.html
评论列表(0条)