本指南示範如何利用 JSON Server 建立模擬 API 並將其無縫整合到使用 TypeScript 建置的 Next.js 15 應用程式中。 我們將介紹設置,透過實際範例說明每個 HTTP 方法(GET、POST、PUT、DELETE),並重點介紹 Next.js 15 的新 use
資料取得功能的使用。
了解 JSON 伺服器
JSON Server 使用簡單的 JSON 檔案簡化了 RESTful API 的建立。其主要特點包括:
為什麼採用 Next.js 15 的 JSON 伺服器?
這種組合有幾個優點:
設定 JSON 伺服器
在 Next.js 專案中安裝 JSON Server 作為開發依賴項:
npm install --save-dev json-server
在專案根目錄中建立一個db.json
檔案:
{ "users": [ { "id": 1, "name": "John Doe", "email": "john@example.com" }, { "id": 2, "name": "Jane Smith", "email": "jane@example.com" } ] }
將腳本新增至您的package.json
以啟動伺服器:
"scripts": { "json-server": "json-server --watch db.json --port 4000" }
--delay
--delay
標誌模擬網路延遲,對於測試載入狀態很有用:
"scripts": { "json-server": "json-server --watch db.json --port 4000 --delay 1000" }
這引入了 1 秒的延遲。 使用以下命令啟動伺服器:
npm run json-server
您的 API 可以在 http://localhost:4000
存取。
使用 HTTP 方法
GET 方法取得資料。 以下是檢索使用者的方法:
'use client'; import { use } from 'react'; async function fetchUsers() { const res = await fetch('http://localhost:4000/users'); if (!res.ok) { throw new Error('Failed to fetch users'); } return res.json(); } export default function UsersPage() { const users = use(fetchUsers()); return ( <div> <h1>Users</h1> <ul> {users.map((user: { id: number; name: string }) => ( <li key={user.id}>{user.name}</li> ))} </ul> </div> ); }
說明:
fetchUsers
:非同步取得使用者資料。 use
:用於伺服器端資料取得的 Next.js 15 掛鉤。 POST 方法建立新記錄:
'use client'; import { useState } from 'react'; export default function AddUser() { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const handleAddUser = async () => { const res = await fetch('http://localhost:4000/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, email }), }); if (res.ok) { alert('User added successfully!'); } }; return ( <div> <h2>Add New User</h2> <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} /> <button onClick={handleAddUser}>Add User</button> </div> ); }
PUT 方法修改現有記錄:
'use client'; import { useState } from 'react'; export default function UpdateUser() { // ... (similar to POST, but with an ID field and PUT request) }
DELETE 方法刪除記錄:
'use client'; import { useState } from 'react'; export default function DeleteUser() { // ... (similar to PUT, but with a DELETE request) }
最佳實務
.env
檔案中,以便更好地進行設定管理。 --delay
測試載入狀態並模擬較慢的網路條件。 結論
JSON Server 是 Next.js 15 前端開發的寶貴資產,提供了一種簡單而有效的方法來模擬 API 並顯著加速開發。 這些適用於所有 HTTP 方法的範例可讓您將 JSON Server 無縫整合到您的專案中。
以上是Next.js 的 JSON 伺服器您需要了解的一切的詳細內容。更多資訊請關注PHP中文網其他相關文章!