简体   繁体   中英

Failed to load resource: the server responded with a status of 404 (Not Found) Node.js socket.io

I'm trying to create a server using Node.js and socket.io and it starts perfectly. However, when I'm trying to visit the site of my server through the browser, he writes " Cannot Get / " and in the console gives an error " Failed to Load Resource: The Server Respondd with A Status of 404 (Not Found) ". For two days I'm trying to understand where the problem and I will be very grateful to your help. Here is my server code:

const express = require("express");
var http = require("http");
const app = express();
const port = process.env.PORT || 5000;
var server = http.createServer(app);
var io = require("socket.io").listen(server);

//middlewre
app.use(express.json());

io.on("connection", (socket) => {
    console.log("connected");
    console.log(socket.id, "has joined");
    socket.on("/test", (msg) => {
        console.log(msg);
    })
});

server.listen(port, "0.0.0.0", () => {
    console.log("server started");
});

Your server is currently not set up to handle any other http traffic than Websocket connection upgrade requests, which you can not make by entering a url in your browser. Also, the browser is not equipped to negotiate this connection upgrade or to keep the Websocket connection working once established. For this you need some javascript code to run on the client side.

The socket.io library provides everything you need, look at a minimally working example at the link provided below. You should basically just set up your server to serve an html document which provides a context from which the whole websocket connection upgrade can be managed - and the connection maintained - by the socket.io library.

https://socket.io/docs/v2#Minimal-working-example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM