socket.io hardcoded vs dynamic connection url

我怕爱的太早我们不能终老 提交于 2020-01-29 09:34:51

问题


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');

Instead of simply:

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

Or even:

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/21886773/socket-io-hardcoded-vs-dynamic-connection-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!