我正在创建一个基于 Nodejs 中的 websocket 作为后端和 ionic 4 应用程序作为前端的服务器,当我尝试连接到我的服务器时,我收到此错误
GET http://localhost:8080/socket.io/?EIO=3&transport=polling&t=McNiz_D 404(未找到)
这是我的服务器代码
const PORT = 8080;
const WebSocket = require("ws").Server;
var express = require("express");
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header("Access-Control-Allow-Credentials", true);
next();
});
var http = require("http").createServer(app);
http.listen(PORT, "localhost", function() {
console.log("listening in http://localhost:" + PORT);
});
const wss = new WebSocket({ server: http });
wss.on("connection", function connection(ws) {
ws.on("message", function incoming(message) {
console.log("received: %s", message);
});
ws.send("I am server ^_^");
});
最佳答案
为了将来的引用以及您想要更多说明,发生这种情况是因为在后端使用 websockets 协议(protocol)并在前端使用 socket.io 而不是普通的 WebSockets 客户端。
当socket.io想要连接到服务器时upgrade请求发送到 http://localhost:8080/socket.io/?EIO=3&transport=polling&t=McNiz_D 404
这个路径。由于后端没有配置socket io服务器,显然express服务器发送404 not find
而不是升级响应。
关于node.js - 获取http ://localhost:8080/socket. io/?EIO=3&transport=polling&t=McNiz_D 404(未找到),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55249839/