mpetazzoni/sse.js

application/json payload not working

Closed this issue · 5 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?

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

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

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)?

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