客户端未从Express.js服务器接收到服务器发送的事件。

huangapple go评论79阅读模式
英文:

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(&#39;/stream/:walletAddress&#39;, async (req, res, next) =&gt; {
	try {
		res.set({
			Connection: &#39;keep-alive&#39;,
			&#39;Content-Type&#39;: &#39;text/event-stream&#39;,
			&#39;Cache-Control&#39;: &#39;no-cache&#39;,
			&#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;
		});
		res.flushHeaders();

        let x = 0;
		const id = setInterval(() =&gt; {
			res.write(`event: message\n`);
			res.write(`data: ${x++}\n\n`);
		}, 2000);

		res.on(&#39;close&#39;, () =&gt; {
			console.log(&#39;Client closed.&#39;);
			clearInterval(id);
		});
	} catch (err) {
		next(err);
	}
});

Next.js (React) Code:

import { API_URL } from &#39;config&#39;;
import { useWalletStore } from &#39;src/stores&#39;;


export const FetchTxsProvider = ({ children }) =&gt; {
	const safeSdkReader = useWalletStore(state =&gt; state.safeSdkReader);

	useEffect(() =&gt; {
		const eventSource = new EventSource(
			`${API_URL}/transactions/stream/${safeSdkReader.getAddress()}`
		);

		eventSource.onopen = function (e) {
			console.log(&#39;Successfully connected.&#39;);
		};

		eventSource.onerror = function (err) {
			console.error(err);
			eventSource.close();
		};

        // ! Should fire here but doesn&#39;t!
		eventSource.onmessage = function (event) {
            console.log(&#39;Event: &#39;, event);
		};

		return () =&gt; {
			console.log(&#39;Connection closed.&#39;);
			eventSource.close();
		};
	}, [safeSdkReader]);

	return &lt;&gt;{children}&lt;/&gt;
};

答案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 &#39;Content-Encoding&#39;: &#39;none&#39;.

res.writeHead(200, {
  &#39;Content-Type&#39;: &#39;text/event-stream&#39;,
  &#39;Cache-Control&#39;: &#39;no-cache&#39;,			
  &#39;Content-Encoding&#39;: &#39;none&#39;,
  &#39;Connection&#39;: &#39;keep-alive&#39;,
  &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;
});

答案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?

huangapple
  • 本文由 发表于 2023年5月31日 23:33:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定