6

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?

Aniruddha Bhondwe
  • 821
  • 12
  • 18
  • 9
    Make the URLs relative to the root of the domain, eg `'/timer/check/'` – Rory McCrossan Sep 08 '16 at 07: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 Sep 08 '16 at 07:50

3 Answers3

3

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/

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42
  • I dont know who has down voted.. but this works... is any reason for down vote? – Haresh Vidja Sep 08 '16 at 08:01
  • @RoryMcCrossan, please check it... I have done this in may projects... it applied in JS also. – Haresh Vidja Sep 08 '16 at 08:02
  • It works in modern browsers but it's unsupported for use with JS urls in older ones. I'd still suggest you avoid the `` tag as it has plenty of caveats which can ruin your day, see http://stackoverflow.com/questions/1889076/is-it-recommended-to-use-the-base-html-tag – Rory McCrossan Sep 08 '16 at 08:12
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
Shakir Ahamed
  • 1,290
  • 3
  • 16
  • 39
0

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.

Rehban Khatri
  • 924
  • 1
  • 7
  • 19