我有一个组件,该组件在安装时会向服务器发出请求,以获取(很长)名称列表。为了不妨碍组件的渲染(因为它只能使用非空列表进行渲染),我想使用套接字向它发送一系列小得多的列表,而不是使用{{ 1}}(大约需要4秒钟)。
为此,我在快递服务器中使用了socket.io,但出现404错误。这是我的设置:
客户(组件)
res.send()
此组件的父级是调用 import socketIOClient from 'socket.io-client';
componentDidMount() {
console.log('trying to put on sock');
const socket = socketIOClient();
socket.on('names', data => console.log('data'));
}
路由的父级。
服务器
api/v1/names
最终发生的是我的控制台中的错误: const express = require('express');
const socketIo = require('socket.io');
const http = require('http');
const app = express();
app.use(express.static(path.resolve(__dirname, '../build')));
const server = http.createServer(app);
const io = socketIo(server);
app.get('/api/v1/names', (req, res) => {
res.set('Content-Type', 'application/json');
getNames().then((result) => {
// res.send({ result }); what I was doing before (~4 seconds)
io.on('connection', (socket) => {
console.log('New client connected');
// chunk the results into 10 smaller arrays
let final = false;
const parts = _.chunk(result, 10);
parts.forEach((part, pIx) => {
if (pIx === parts.length - 1) final = true;
// Will this be async or not? we shall see...
socket.emit('names', { result: part, final });
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
});
});
。 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=123kj123b 404 (Not Found)
中的日志永远不会发生。看到了io.on('connection')
日志,所以我知道它正在尝试监听。
答案 0 :(得分:0)
您可以引用此链接socket.io-client
var socket = require('socket.io-client')('http://localhost:4200');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
需要像这样与服务器连接。