socket.io硬编码与动态连接网址 [英] socket.io hardcoded vs dynamic connection url

查看:41
本文介绍了socket.io硬编码与动态连接网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这里的大多数教程,示例和问题都使用本地IP或 localhost (或任何其他硬编码路径),如下所示:

Why most tutorials, examples and questions here use the local IP or localhost (or any other hard-coded path) like this:

var socket = io.connect('http://127.0.0.1:3700');

而不是简单地:

var socket = io.connect(document.location.protocol+'//'+document.location.host);

甚至:

var socket = io.connect();

是否有像这样使它动态化的风险?有什么更好的方法可以使我的脚本在本地和生产环境中工作,而不必每次都更改此值?

Are there any risks making it dynamic like this? Are there any better way to make my script work locally and in production without having to change this value every time?

推荐答案

如果您使用的是动态连接网址,而不是硬编码的网址,则看不到任何风险.

I don't see any risks involved, if you have a dynamic connection url instead of a hard-coded one.

在我看来,像您的第一个示例中那样的硬编码url更便于初学者理解.第二个示例可能令人困惑.(实际上,我还必须检查document.location.host是否包含端口号).我猜这就是大多数示例和教程使用硬编码变体的原因.

In my opinion a hard-coded url like in your first example is more easier for beginners to understand. The second example could be confusing. (Actually I also had to check, if document.location.host contains the port number or not). And that's why most examples and tutorials use the hard-coded variant, I guess.

如果第三个示例在您的开发和生产环境中均适用,则应使用它.但是,如果套接字在与应用程序其余部分不同的端口和/或主机上运行,​​则它将无法正常工作,因此有必要在脚本中的某个位置对其进行硬编码.

If the third example works in both your development and production environment, you should use it. But in cases where the socket is running on a different port and/or host than the rest of the application, it does not work and it is necessary to hard-code it somewhere in the script.

这篇关于socket.io硬编码与动态连接网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆