每次 Socket.IO 连接到我的 Heroku 应用程序时,都会返回 400 Bad Request。我该如何解决这个问题?
我有一个使用 Socket.IO 的 Node.js Web 应用程序。在本地开发中没有问题,但是当我将应用程序部署到 Heroku 时,每个 socket.io 连接都会返回 400 Bad Request。我尝试手动将传输方法设置为 websocket、轮询等,但仍然不起作用。我还为我的 dyno 打开了 session 关联性。
在我的服务器中
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
const namespace = io.of('/client-web-app');
客户端通过以下方式连接
const socket = io('/client-web-app')
像平常一样。
浏览器控制台记录以下内容:
polling-xhr.js:269 POST https://<app-name>.herokuapp.com/socket.io/?EIO=3&transport=polling&t=Mo5GHwF&sid=7Pn_tN47tE2NqFKMAAAc 400 (Bad Request)
还有 GET 和 websocket 版本的请求
同时,Heroku 记录以下内容:
at=info method=POST path="/socket.io/?EIO=3&transport=polling&t=Mo5GjRq&sid=wSTQhI8NQRpLbb3xAAAm" host=<app-name>.herokuapp.com request_id=da83df98-0522-4e0a-b0cc-fdbc3304b7f8 fwd="110.54.138.89" dyno=web.1 connect=0ms service=2ms status=400 bytes=296 protocol=https
2019-08-12T09:57:28.339289+00:00 app[web.1]: device disconnected
2019-08-12T09:57:28.628468+00:00 heroku[router]: at=info method=GET path="/socket.io/?EIO=3&transport=polling&t=Mo5GjRs&sid=wSTQhI8NQRpLbb3xAAAm" host=<app-name>.herokuapp.com request_id=99ba8299-6f8a-448f-a8ce-d0b34b4a062f fwd="110.54.138.89" dyno=web.1 connect=0ms service=2ms status=400 bytes=228 protocol=https
将我的实际应用程序名称替换为 <app-name>
由于原因。
最佳答案
找到了解决我自己问题的方法。在这里发帖以防其他人遇到与我相同的问题。只需明确声明您将使用 websocket
作为传输。
所以在你的socket.io服务器中:
const app = express();
const server = http.createServer(app);
const io = socketIO(server, {transports: ['websocket']});
在你的socket.io客户端中:
const socket = io('/client-web-app', {transports: ['websocket']});
Heroku 似乎仅支持 websocket
作为 socket.io 传输。
关于javascript - Heroku 返回 400 错误请求响应 (Socket.IO Node.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57459115/