[英]GET http://localhost:8563/socket.io/?EIO=3&transport=polling&t=NEsUPis 404 (Not Found)
[英]Can't connect socket.io node server to react frontend. “POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MoHNIJT 404 (Not Found)”
我在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.