英文:
Client not receiving Server Sent Events from Express.js server
问题
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}</>;
};
英文:
I have a Next.js (React) client that I've setup to listen to Server-Sent Events from my Node.js/Express.js server, but it doesn't seem to be receiving messages for some reason.
The open
and error
events of EventSource
are working properly, but whenever I use .onmessage
it doesn't detect anything.
What am I doing wrong?
Express.js Code:
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) Code:
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
得分: 2
不知道为什么,但标题中缺少了 Content-Encoding: none
。
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Content-Encoding': 'none',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
英文:
Don't know why, but the headers were missing 'Content-Encoding': 'none'
.
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Content-Encoding': 'none',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
答案2
得分: 0
很多时候在处理发布/订阅系统时,订阅者或消费者可以连接到代理,该代理可以触发所有启动事件,但没有收到任何消息。您确定已连接到正确的目标吗?
Next.js正在寻找/transactions/stream/...
,而Express.js似乎可能只指向资源/stream/...
。这是否是预期的行为?
英文:
A lot of times dealing with pub/sub systems, the subscriber or consumer can connect to the broker which can fire all of the events of starting, but getting no messages. Are you sure you’re connected to the right destination?
The Next.js is looking for /transactions/stream/...
where Express.js looks like it might be pointing to just the resource /stream/...
. Is that expected?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论