我正在使用socket.io将Express Server中的实时数据发送到Reactjs客户端,但是数据仅在来自React客户端的获取请求时发送。
代码运行正常,但是当我向Express服务器和客户端中的提取方法添加路由时,则无法正常工作。
服务器端(server.js):
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const axios = require("axios");
const PORT = process.env.PORT || 8001;
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.get('/system/overview',(req,res) => {
io.on("connection", socket => {
console.log("New client connected"), setInterval(
() => getAndEmitData(socket),
1000
);
socket.on("disconnect", () => console.log("Client disconnected"));
});
const getAndEmitData = async socket => {
try {
const response = await axios.get(
"https://api.darksky.net/forecast/927aa7bef57ca7b2422"
);
socket.emit("temp", response.data.currently.temperature);
} catch (error) {
console.error(`Error: ${error.code}`);
}
};
})
server.listen(PORT, () => console.log(`Listening on port ${PORT} ...`));
客户端(Overview.js组件):
import socketIOClient from "socket.io-client";
...
class Overview extends Component {
constructor() {
super();
this.state = {
response: false,
endpoint: "http://localhost:8001"
};
}
componentDidMount() {
const { dispatch } = this.props;
const { endpoint } = this.state;
dispatch({
type: 'profile/fetchAdvanced',
});
const socket = socketIOClient(endpoint);
fetch('http://localhost:8001/system/overview', {
method: 'get',
})
.then(res => res.json())
.then(data => {
socket.on("temp", data => this.setState({ response: data }));
})
}
...
没有错误,但是执行ComponentDidMount函数时,服务器无法处理来自响应客户端的GET请求! 最好的方法是什么? 谢谢...