无法连接socket.io节点服务器以响应前端。 “ POST http:// localhost:3000 / socket.io /?EIO = 3&transport = polling&t = MoHNIJT 404(未找到)”

时间:2019-08-14 21:26:59

标签: javascript node.js reactjs express socket.io

我已经在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配合使用的任何建议

1 个答案:

答案 0 :(得分:0)

您需要使用http库而不是https库。

server.listen(3500)不支持https。如果出于某些原因确实需要使用它,则可以引用this answer

另外,在您的客户端上,您需要告诉套接字库主机的URL,否则将默认为window.location,如here in the docs所述,这似乎是您的情况,因为您提到请求是定向到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)