@@ -300,18 +300,35 @@ app.get("/posts", async (request, response) => {
300300
301301### 手順7
302302
303- [ Fetch APIによるデータの送信の章 ] ( /docs/web-servers/fetch-api-post/ ) の演習問題2と同様にして 、ブラウザ側で、定期的に` /posts ` にGETリクエストを発行し、受け取ったレスポンスに基づいてメッセージの一覧を表示するようにしてください。また、メッセージを入力し、送信ボタンを押すと、` /send ` に対してPOSTリクエストでメッセージの内容を送信するようにしてください。
303+ 前頁での演習問題2と同様にして 、ブラウザ側で、定期的に` /posts ` にGETリクエストを発行し、受け取ったレスポンスに基づいてメッセージの一覧を表示するようにしてください。また、メッセージを入力し、送信ボタンを押すと、` /send ` に対してPOSTリクエストでメッセージの内容を送信するようにしてください。
304304
305305<Answer title = " 手順7まで" >
306306
307+ ``` javascript title="main.mjs (サーバーとして動作するJavaScript)"
308+ import express from " express" ;
309+ import { PrismaClient } from " ./generated/prisma/index.js" ;
310+
311+ const app = express ();
312+ const client = new PrismaClient ();
313+ app .use (express .json ());
314+ app .use (express .static (" ./public" ));
315+
316+ app .get (" /posts" , async (request , response ) => {
317+ const posts = await client .post .findMany ();
318+ response .json (posts);
319+ });
320+
321+ app .listen (3000 );
322+ ```
323+
307324``` html title="public/index.htmlの抜粋"
308325<ul id =" message-list" ></ul >
309326<input id =" message-input" placeholder =" メッセージ" />
310327<button id =" send-button" type =" button" >送信</button >
311- <script type = " module " src =" ./script.mjs " ></script >
328+ <script src =" ./script.js " ></script >
312329```
313330
314- ``` javascript title="public/script.mjs (ブラウザ上で動作するJavaScript)"
331+ ``` javascript title="public/script.js (ブラウザ上で動作するJavaScript)"
315332setInterval (async () => {
316333 const response = await fetch (" /posts" );
317334 const posts = await response .json ();
@@ -327,9 +344,10 @@ setInterval(async () => {
327344}, 1000 );
328345
329346document .getElementById (" send-button" ).onclick = async () => {
330- const message = document .getElementById (" message-input" ).value ;
347+ const messageInput = document .getElementById (" message-input" );
348+ const message = messageInput .value ;
331349 await fetch (" /send" , {
332- method: " post " ,
350+ method: " POST " ,
333351 headers: { " Content-Type" : " application/json" },
334352 body: JSON .stringify ({ message: message }),
335353 });
@@ -360,7 +378,6 @@ app.post("/send", async (request, response) => {
360378<Answer title = " 手順9まで" >
361379
362380``` javascript title="main.mjsの抜粋 (サーバーとして動作するJavaScript)"
363- app .use (express .urlencoded ({ extended: true }));
364381app .post (" /send" , async (request , response ) => {
365382 await client .post .create ({ data: { message: request .body .message } });
366383 response .send ();
0 commit comments