Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

node.js - Socket.io client requests fail when frontend and backend run on different ports

I want to use Socket.io with a React frontend and NodeJS & Express backend but have both running on different ports for development (Fontend: 3000; Backend: 8080).

When the Socket.io-Client has loaded my frontend executes var socket = io('http://localhost:8080'); and then automatically makes a GET request to http://localhost:8080/socket.io/?EIO=4&transport=polling&t=NSlH7of. That request should normally return something like 0{"sid":"XXX","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000} but the Chrome Dev Tools say that the status is (failed) net::ERR_FAILED. There also is no response available in the Dev Tools.

However when I run the GET request in my HTTP-Client it returns exactly what I expect it to return.

That error looks like it's caused by the Socket.io-Client but I get no error whatsover besides the failed GET request. When I run everything on one port (Frontend served with webpack by the backend) the request goes through as expected.

I would appreciate any help! Thanks!

server.js

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

//Serve static react app
app.use(express.static('dist'));
app.use('/app', express.static('dist'));
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '../../../' + '/dist/index.html'));
});

io.on('connection', (socket) => {
    console.log('Connected')
    socket.on('join-game', (gameId, userId) => {
        console.log(gameId, userId);
    })
})

http.listen(process.env.PORT || 8080, () => {
    console.log(`Listening on port ${process.env.PORT || 8080}!`);
});
question from:https://stackoverflow.com/questions/65859439/socket-io-client-requests-fail-when-frontend-and-backend-run-on-different-ports

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to hit port 8080 for your socket.io connection, you must set up a server for that port in your nodejs program (your back end). Code running in browsers (front-end code in React parlance) like your code

var socket = io('http://localhost:8080')

can only originate connection requests. And, if no server is listening for those requests, you get the failure status that your devtools showed you.

By the way, you'll be wise to make your nodejs server program use just one port. With just one port, it's much simpler to deploy to a production server.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...