Hard Coded URLs

I have a request for hard-coded URLs. When creating a mail call from JavaScript using jquery, I do it like$.post('http://localhost:8000/timer/check/'

Now it works fine on my development server. When I need to deploy it to another server, I need to manually change the entire URL in the code. So how to avoid hard coding errors?

+4
source share
3 answers

To do this, you need to use the tag below in the meta tag

<head>
<base href="{{your base url_here}}">
</head>

After that, you need to write a path relative to this base url.

Example

<head>
    <base href="http://localhost:8000/timer/check/">
</head>

If the full url http://localhost:8000/timer/check/test.php. Now you can write about the base url 'test.php'in the ajax call.

: https://jsfiddle.net/ptLzs7m5/1/

+1

 var host = window.location.hostname;
 var url = host + "/" + timer/check/;

URL- post

 window.location.protocol   //you'll get your protocol `http` or `https` 
 window.location.port       //this will return the port
+1

-

1) $.post('./timer/check'). URL- ()

2) , . url dev prod url .

3) . (Dev Prod) . -

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
}

, .

0

Source: https://habr.com/ru/post/1653977/


All Articles