问题
I have created a frontend in react and a backend in express nodejs, and I am using socket.io for the client and server to communicate.
When I load the react page I get the following error every second:
Failed to load resource: the server responded with a status of 404 (Not Found)
I have set the frontend to run on port 3000 and the server to run on port 3500. The failed connect requests are being sent to the address: http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MoHUt8D
Below is the setup for the node backend:
const bodyParser = require('body-parser');
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin',
'https://www.localhost:3000');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PATCH, PUT');
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
const server = https.createServer(app);
var io = require('socket.io')(server);
console.log('Server listening on port 3500.');
server.listen(3500);
And the client side connects as follows:
import openSocket from "socket.io-client";
const hostURL = "http://localhost:3500";
const socket = openSocket()
Any advice on how to stop the error and have the front and backend working with socket.io
回答1:
You need to use the http
library instead of the https
one.
server.listen(3500)
does not support https. If for some reason you do need to use it, you can reference this answer.
Also, on your client you need to tell the socket library the URL of the host, otherwise it will default to window.location
as mentioned here in the docs which seems to be your case as you mentioned the requests are directed towards localhost:3000
and your server is on localhost:3500
so change this
import openSocket from "socket.io-client";
const hostURL = "http://localhost:3500";
const socket = openSocket()
to this
import openSocket from "socket.io-client";
const hostURL = "http://localhost:3500";
const socket = openSocket(hostURL)
来源:https://stackoverflow.com/questions/57502287/cant-connect-socket-io-node-server-to-react-frontend-post-http-localhost30