Heroku 返回 400 Bad Request Response (Socket.IO Node.js)

Jan*_*ain 1 javascript heroku node.js socket.io

每次 Socket.IO 连接到我的 Heroku 应用程序时,都会返回 400 Bad Request。我该如何解决?

我有一个使用 Socket.IO 的 Node.js Web 应用程序。在本地开发中没有问题,但是当我将应用程序部署到 Heroku 时,每个 socket.io 连接都会返回 400 Bad Request。我已经尝试将传输方法手动设置为 websocket、轮询和两者,但它仍然不起作用。我还为我的 dyno 开启了会话关联。

在服务器中我有

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

const namespace = io.of('/client-web-app');

Run Code Online (Sandbox Code Playgroud)

客户端通过

const socket = io('/client-web-app')
Run Code Online (Sandbox Code Playgroud)

就像你通常做的那样。

浏览器控制台记录以下内容:

polling-xhr.js:269 POST https://<app-name>.herokuapp.com/socket.io/?EIO=3&transport=polling&t=Mo5GHwF&sid=7Pn_tN47tE2NqFKMAAAc 400 (Bad Request)
Run Code Online (Sandbox Code Playgroud)

还有一个 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
Run Code Online (Sandbox Code Playgroud)

<app-name>出于某些原因替换了我的实际应用程序名称。

Jan*_*ain 5

找到了解决我自己问题的方法。在这里发布以防其他人遇到与我相同的问题。只需明确说明您将websocket用作交通工具。

所以在你的 socket.io 服务器中:

const app = express();
const server = http.createServer(app);
const io = socketIO(server, {transports: ['websocket']});
Run Code Online (Sandbox Code Playgroud)

并在您的 socket.io 客户端中:

const socket = io('/client-web-app', {transports: ['websocket']});

似乎 Heroku 只支持websocket作为 socket.io 传输。