我的客户端应用程序中的以下代码:
const socket = io('${location.protocol}//${location.hostname}:8090');
在我的浏览器中出现以下错误:
XMLHttpRequest cannot load http://${location.protocol}/socket.io/?EIO=3&transport=polling&t=LRLUtss. Cross origin requests are only supported for HTTP.
我的客户端代码是通过 npm start
使用 Node.js 运行的,因此当我更新代码时,“http://localhost:3000 ”会在我的浏览器中自动刷新。
最佳答案
看起来 ${location.protocol}
在字符串中没有被替换,因此当 socket.io 尝试使用 URL 时它仍然在 URL 中。这可能是因为浏览器不支持特定的 ES6 功能。
您可以通过使用字符串添加的老式方式构造 URL 字符串来解决此问题。
const socket = io(location.protocol + '//' + location.hostname + ':8090');
而且,如果您希望替换在支持的情况下可靠地工作,您还应该使用反引号作为字符串分隔符。
关于javascript - "Cross origin requests are only supported for HTTP."与 Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39202161/