項目基本介紹:使用React,webpack,socket.io-client, Node.js, Express, socket.io 等技術,採用前後端分離開發。
實現項目中的聊天室時遇到報錯,一直請求下面的連接:
GET http://localhost:3030/socket.io/?EIO=3&transport=polling&t=N8HrzIR 404 (Not Found)
Failed to load http://localhost:3030/socket.io/?EIO=3&transport=polling&t=N8HrzIR: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access. The response had HTTP status code 404.
問題大意指跨域了,可WebSocket是可以跨域的。
還不太清楚原因是什麼,若有知道原因的朋友請指教,但最終解決了,還是記錄一下,如下:
給socket.io賦值一個新的端口。
const app = express()
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.listen(3031) //!!!