GET http:// localhost:8080 / socket.io /?EIO = 3&transport = polling&t = McNiz_D 404(未找到)

时间:2019-03-19 20:55:34

标签: node.js websocket socket.io

我在nodejs中基于websocket创建服务器作为后端,而在ionic 4应用程序中作为前端,当我尝试连接到服务器时出现此错误

GET http://localhost:8080/socket.io/?EIO=3&transport=polling&t=McNiz_D 404 (Not Found)

这是我的服务器代码

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 ^_^");
});

1 个答案:

答案 0 :(得分:1)

为将来参考,并且需要进一步说明,发生这种情况是因为在后端使用websockets协议,在前端使用socket.io而不是普通的WebSockets客户端。


当socket.io要连接到服务器时,upgrade请求将发送到http://localhost:8080/socket.io/?EIO=3&transport=polling&t=McNiz_D 404此路径。由于后端没有配置套接字io服务器,因此显然快递服务器发送404 not found而不是升级响应。