我有一个Next.js(React)客户端,我已经设置它来监听来自我的Node.js/Express.js服务器的Server-Sent Events,但由于某种原因,它似乎没有接收消息。EventSource
的open
和error
事件工作正常,但每当我使用.onmessage
时,它都检测不到任何东西。
我做错了什么?
Express.js代码:
router.get('/stream/:walletAddress', async (req, res, next) => {
try {
res.set({
Connection: 'keep-alive',
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*'
});
res.flushHeaders();
let x = 0;
const id = setInterval(() => {
res.write(`event: message\n`);
res.write(`data: ${x++}\n\n`);
}, 2000);
res.on('close', () => {
console.log('Client closed.');
clearInterval(id);
});
} catch (err) {
next(err);
}
});
Next.js(React)代码:
import { API_URL } from 'config';
import { useWalletStore } from 'src/stores';
export const FetchTxsProvider = ({ children }) => {
const safeSdkReader = useWalletStore(state => state.safeSdkReader);
useEffect(() => {
const eventSource = new EventSource(
`${API_URL}/transactions/stream/${safeSdkReader.getAddress()}`
);
eventSource.onopen = function (e) {
console.log('Successfully connected.');
};
eventSource.onerror = function (err) {
console.error(err);
eventSource.close();
};
// ! Should fire here but doesn't!
eventSource.onmessage = function (event) {
console.log('Event: ', event);
};
return () => {
console.log('Connection closed.');
eventSource.close();
};
}, [safeSdkReader]);
return <>{children}</>
};
1条答案
按热度按时间dy2hfwbg1#
在处理pub/sub系统的很多时候,订阅者或消费者可以连接到代理,该代理可以触发所有启动事件,但没有消息。您确定连接到正确的目的地吗?
Next.js正在查找
/transactions/stream/...
,而Express.js看起来可能只指向资源/stream/...
。这是意料之中的吗?