服务器通过Fastify sse发送事件的CORS问题



我正在使用Fastify服务器将SSE事件发送到React前端。虽然在本地一切都很好,但我在部署Nginx后遇到了问题。前端和服务器不在同一个域上,尽管我将cors原点设置为"0"*"在服务器上,其他调用解决没有问题,对于服务器发送的事件端点,我只得到

阻止跨来源请求:同源策略不允许读取位于的远程资源https://example.com/events.(原因:CORS请求未成功(。状态代码:(null(。

以下是如何使用@fastify/corsfastify-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)
}

问题出在nginx配置中。多亏了EventSource/Server通过Nginx发送的事件,我使用放在Nginx conf的location中的以下内容解决了这个问题:

proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;

最新更新