sse.js icon indicating copy to clipboard operation
sse.js copied to clipboard

application/json payload not working

Open CocoaPriest opened this issue 1 year ago • 4 comments

As soon as I change Content-Type to application/json it stops to receive events from the server:

const payload = JSON.stringify({ prompt: "test" });
console.log(payload);

var subscription = new SSE("http://localhost:3002/api/process", {
        headers: { "Content-Type": "application/json" },
        payload: payload,
});

On backend, I'm using express with app.use(express.json()); and I see the payload with console.log(req.body.prompt);, so that's not the issue.

plain text also works as expected, but in that case I can't read req.body (also as expected).

So the problem is really that my callbacks aren't getting called.

Any ideas?

CocoaPriest avatar Feb 05 '24 14:02 CocoaPriest

Found that after removing this code: req.on("close", () => res.end()); it works again. But I'm not sure if it's the right behavior.

CocoaPriest avatar Feb 05 '24 15:02 CocoaPriest

@CocoaPriest Given your second comment, this seems like a backend-side issue. Note that you have to watch for response buffering/flushing on the server-side here. Are you sure your Express.js service is actually returning anything / flushing the response buffer appropriately after each event?

mpetazzoni avatar Feb 05 '24 18:02 mpetazzoni

yes, pretty sure. Again, it works when using regular sse.

CocoaPriest avatar Feb 05 '24 20:02 CocoaPriest

Can you share what the browser devtools show for the request to /api/process? Any other difference between when it works (with text/plain) and when it doesn't (with application/json)?

mpetazzoni avatar Feb 06 '24 00:02 mpetazzoni

I was fairly certain this isn't from anything sse.js is doing, but I built an example regardless to validate, and I can't reproduce this issue. Events come in normally.

Screenshot 2024-08-06 at 12 21 15 PM

mpetazzoni avatar Aug 06 '24 19:08 mpetazzoni