我正在使用Fastify服务器将SSE事件发送到一个反应性前端。虽然在本地一切都很好,但我曾经在Nginx后面部署过一些问题。前端和服务器不在同一域中,虽然我将cors原点设置为服务器上的"*“,而另一个调用解决了没有问题,但对于服务器发送事件端点,只有我得到。
跨源请求被阻止:相同的原产地策略不允许在https://example.com/events上读取远程资源。(原因: CORS请求没有成功)。状态代码:(null)。
以下是使用@fastify/cors
和fastify-sse-v2
配置Fastify的方式
import fastifyCors from "@fastify/cors";
import FastifySSEPlugin from "fastify-sse-v2";
// ...
await this.instance.register(FastifySSEPlugin, { logLevel: "debug" });
await this.instance.after();
await this.instance.register(fastifyCors, { origin: "*" });
然后发送基于postgres pubsub的事件,包括:
await pubsub.addChannel(TxUpdateChannel);
reply.sse(
(async function* () {
for await (const [event] of on(pubsub, TxUpdateChannel)) {
yield {
event: event.name,
data: JSON.stringify(event.data),
};
}
})()
);
在前端,我使用事件源以便添加授权头:
import EventSource from "eventsource";
// ...
const source = new EventSource(`${SERVER_URL}/transaction/events`, {
headers: {
'Authorization': `Bearer ${jwt}`,
},
});
source.onmessage = (event) => {
console.log('got message', event)
getUserData()
}
source.onopen = (event) => {
console.log('---> open', event)
}
source.onerror = (event) => {
console.error('Event error', event)
}
发布于 2022-07-27 13:48:33
问题在于nginx的配置。多亏了EventSource /Server-通过Nginx发送事件,我使用nginx的location
中的以下内容解决了这个问题:
proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;
https://stackoverflow.com/questions/73112330
复制相似问题