在上一篇文章,有說明如何用 useState 來管理表單輸入,並在送出後看到 console 的結果。
而在這篇文章,我們要利用 POST 方法,把表單資料送到真的後端 API,完成新增的功能。
當使用者按下「送出」時,會先把輸入的值收集起來,放到一個物件裡:
const blog = { title, body, author };
這個 blog 物件看起來會像這樣:
{
"title": "標題...",
"body": "內容…",
"author": "作者..."
}
用 fetch 把這個物件傳到後端 API:
fetch('http://localhost:8000/blogs/', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(blog)
}).then(() => {
console.log("new blog added");
});
fetch('http://localhost:8000/blogs/', {...})
:指定要請求的 API 位址,這裡是 localhost:8000/blogs/
,表示要把資料送到 /blogs/
method: 'POST'
:使用 POST方法,表示請求的目的是新增一筆資料headers: { "Content-Type": "application/json" }
:在header中告訴伺服器,傳送資料是 JSON 格式body: JSON.stringify(blog)
:fetch 的 body 只能是字串,所以要用 JSON.stringify 把JavaScript物件轉成JSON字串.then(() => { console.log("new blog is added"); })
:當請求完成後,就會執行這段程式,這裡先用 console.log()
來確認請求有正常送出const handleSubmit = (e) => {
e.preventDefault();
const blog = { title, body, author };
fetch('http://localhost:8000/blogs/', {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(blog)
}).then(() => {
console.log('new blog added');
});
};
瀏覽器執行畫面
db.json中會多出一筆資料:
onSubmit={handleSubmit}
會被觸發,進而執行 handleSubmit
這個函式e.preventDefault()
:為了避免表單自動刷新頁面。const blog = { title, body , author};
呼叫 fetch("http://localhost:8000/blogs", {...})
,並設定:method: "POST"
→ 代表是新增資料headers
→ 指定資料格式為 JSONbody: JSON.stringify(blog)
→ 把物件轉成字串送出.then(() => { console.log("new blog added"); })
代表請求成功後,會執行這段程式