【发布时间】:2019-09-16 10:30:15
【问题描述】:
我不断收到这个 GET /socket.io/?EIO=3&transport=polling&t=MfRfeJD 404 4.438 ms - 149 错误,我不知道它来自哪里。
我正在尝试使用 react、socket.io 和 express 将实时聊天集成到我的应用程序中,但我一直收到未找到套接字的错误。我不确定问题出在客户端还是服务器端。它似乎在尝试不断地轮询服务器,但正在返回 404。听起来 socket.io 没有运行,但对我来说一切正常。它也可能与路径有关,但我真的不知道。我尝试向 io 添加不同的路由,例如“http://localhost:5000/”,但仍然找不到套接字。
我让页面显示出来,当我点击发送时显示消息,但我无法连接套接字。
在 app.js 中
const express = require('express');
const http = require('http')
const bodyParser = require('body-parser')
const socketIo = require('socket.io')
var app = express();
const server = http.createServer(app)
const io = socketIo(server)
var PORT = process.env.PORT || 5000;
app.post('/', (req, res) => {
const { Body, From} = req.body
const message = {
body: Body,
from: From.slice(8),
}
io.emit('message', message)
res.send(`
<Response>
<Message>Thanks for texting!</Message>
</Response>
`)
})
io.on('connection', socket => {
socket.on('message', body => {
socket.broadcast.emit('message', {
body,
from: socket.id.slice(8)
})
})
})
server.listen(PORT);
在 Chat.js 中
import React from "react";
import io from "socket.io-client";
class Chat extends React.Component {
constructor (props) {
super(props)
this.state = { messages: [] }
}
componentDidMount () {
this.socket = io('http://localhost:5000/')
this.socket.on('message', message => {
this.setState({ messages: [message, ...this.state.messages] })
})
}
handleSubmit = event => {
const body = event.target.value
if (event.keyCode === 13 && body) {
const message = {
body,
from: 'Me'
}
this.setState({ messages: [message, ...this.state.messages] })
this.socket.emit('message', body)
event.target.value = ''
}
}
render () {
const messages = this.state.messages.map((message, index) => {
return <li key={index}><b>{message.from}:</b>{message.body} </li>
})
return (
<div>
<h1>Admin Chat</h1>
<input type='text' placeholder='Enter a message...' onKeyUp={this.handleSubmit} />
{messages}
</div>
)
}
}
export default Chat;
【问题讨论】:
标签: javascript reactjs socket.io