我在 react 中创建了一个前端,在express nodejs 中创建了一个后端,并且我正在使用 socket.io 供客户端和服务器进行通信。
当我加载反应页面时,我每秒都会收到以下错误:
Failed to load resource: the server responded with a status of 404 (Not Found)
我已将前端设置为在端口 3000上运行,将服务器设置为在端口 3500 上运行。失败的连接请求正在发送到以下地址: http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MoHUt8D
以下是节点后端的设置:
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);
客户端连接如下:
import openSocket from "socket.io-client";
const hostURL = "http://localhost:3500";
const socket = openSocket()
有关如何停止错误并使前端和后端使用 socket.io 的任何建议
您需要使用http
库而不是https
库。
server.listen(3500)
不支持 https。如果由于某种原因您确实需要使用它,您可以参考此答案。
此外,在您的客户端上,您需要告诉套接字库主机的 URL,否则它将默认为window.location
,如文档中提到的,这似乎是您的情况,因为您提到请求被定向到localhost:3000
并且您的服务器在localhost:3500
所以更改它
import openSocket from "socket.io-client";
const hostURL = "http://localhost:3500";
const socket = openSocket()
对此
import openSocket from "socket.io-client";
const hostURL = "http://localhost:3500";
const socket = openSocket(hostURL)