开发者

Detection of Server

开发者 https://www.devze.com 2023-03-28 02:10 出处:网络
Is there a way to have Javascript autodetect wether its server is local(127.0.0.1) or production(http://www.example.com) and set a variable accordingly?

Is there a way to have Javascript autodetect wether its server is local(127.0.0.1) or production(http://www.example.com) and set a variable accordingly?

For example in PHP is use 开发者_如何转开发this function to do reloads and it works local or production:

  public static function reload()
    {
    $uri = 'http://';
    $uri .= $_SERVER['HTTP_HOST'];
    header('Location: '.$uri);
    }

This way I won't have to remember to edit my local_on variable when uploading my script from development to production.


There's no built in ways like the one you mentioned.

You can, however, user a regex for detecting /localhost/ or 127.0.0.1 on window.location.host

code_environment = (window.location.host.match(/(localhost|127.0.0.1)/)) ? "development" : "production"

That's the direct answer to your question. But you probably need to have a look at build tools for javascript or for your whole web development enterprises, e.g. minifyjs / remove console.log() etc.


You can query window.location.host and see, if it equals 127.0.0.1 or localhost.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号