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

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

问题描述

为什么这里的大多数教程、示例和问题使用本地 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?

推荐答案

如果您使用动态连接 url 而不是硬编码的 url,我认为不会涉及任何风险.

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 硬编码 vs 动态连接 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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