In this video, you wrote the club page’s script. It sends a member’s message to the club’s server and shows the partner’s reply as it arrives, while the server keeps the session’s history.
Key Points
- The page gets a session id once.
crypto.randomUUID()returns a new random id as a string. The script calls it once, when the page loads, so every message from this page shares one practice session. - The page sends only the session id and the message. When the member sends the form, the handler stops the browser’s own submit, which would reload the page. It takes the message and clears the box.
- The page shows the turn, then posts it. It adds two paragraphs to the chat panel, one with the member’s message and an empty one for the reply. Then
fetch()posts{ sessionId, message }as JSON. The history stays on the server. EventSourcecan’t send the message. The browser’sEventSource, made for reading server-sent events, only makesGETrequests, with no body, so the message would never reach the route. Usefetch()with aPOSTbody.await fetch()doesn’t wait for the whole reply. It finishes once the status and headers arrive. With the club’s server, they come together with the first piece, and the rest of the body is still arriving. If the server refused the message, the page puts the server’s text in the reply’s place and stops.- A
TextDecoderStreamturns the body’s bytes into strings. It’s the stream version ofTextDecoder, andpipeThrough()sends the bytes through it. A letter like é stays whole even when a chunk splits it. for awaitreads each piece as it arrives. Each pass adds one piece to the reply’s text. A piece is whatever the network delivered, so it can hold several words. Because you set.textContentinstead of.innerHTML, the reply stays plain text, and nothing in it becomes part of the page’s HTML.- A dropped connection makes the loop throw. If the connection drops partway, the
for awaitloop throws, and this handler doesn’t catch that yet. The next video catches it. - The server remembers the conversation. Mei’s second message didn’t repeat her name, and the page sent no history. The partner could still use her name, because the same session id led the server to send the history holding her first message. In this run, the reply started with “Claro, Mei.” The server’s terminal showed her session at four turns.
The page uses fetch() to post the message. Then it reads the body with for await, as the pieces arrive, and adds each one to the reply as text.