前端与后端协同
连接屏幕与服务器
前端与后端协同 是 CoddyKit 上的免费 Vibe Coding 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Vibe Coding 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Vibe Coding 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Two Halves of One App
Your plan is ready — now let's connect the two halves of a full-stack app. The frontend is everything the user sees and clicks in their browser. The backend is code running on a server that does the heavy lifting: saving data, running logic, talking to a database.
They communicate by sending messages over the internet. In this lesson you'll have AI build both sides and wire them together so a button click on screen actually reaches your server.
How They Talk: Requests and Responses
The frontend and backend talk through HTTP requests. The frontend sends a request ("give me the time entries"); the backend sends back a response (the data, usually as JSON).
You don't need to memorize the details — but knowing this mental model helps you read AI's code and ask better questions when something doesn't connect.
Explain in plain language how a frontend and a backend talk to each other over HTTP.
Use my freelancer hours app as the example: what happens, step by step, when a user clicks 'Add 2 hours for Acme'?
Keep it beginner-friendly and mention the words request, response, and JSON.What Is an API Endpoint?
An API endpoint is a specific URL on your backend that does one job — like /api/entries to list or add time entries. The frontend calls endpoints; the backend answers.
Designing clear endpoints up front keeps your app organized. Ask AI to propose the endpoints your MVP needs based on your features.
For the freelancer hours app, list the API endpoints the MVP needs.
For each endpoint give:
- the method (GET, POST, etc.)
- the path (e.g. /api/entries)
- what it does in one line
- what it returns
Keep it minimal — only endpoints the MVP screens actually call.Generate the Backend Endpoint
Time to build. Ask AI to create one endpoint at a time. Starting small means you can run and test each piece instead of debugging a giant blob.
Notice how the prompt pins the framework and the data shape. The more specific you are, the more the generated code fits the rest of your app.
Using Next.js (App Router) API routes, create a POST endpoint at /api/entries that:
- accepts JSON with { client, hours, date }
- for now, stores entries in an in-memory array (no database yet)
- returns the saved entry as JSON
Also create a GET /api/entries that returns all entries. Add basic input validation and explain the code briefly.Generate the Frontend That Calls It
Now the other half: a screen with a form. When the user submits, the frontend sends the data to your /api/entries endpoint and shows the result.
Tell AI exactly which endpoint to call and what to display. This keeps the two halves in sync.
Build a React component (Next.js page) for adding time entries.
It should:
- show a form with fields: client, hours, date
- on submit, POST the data to /api/entries
- after success, fetch GET /api/entries and list all entries below the form
- show a simple loading and error state
Keep the styling minimal and clean. Explain how the fetch calls connect to my backend.fetch: The Glue Between Them
In the browser, the frontend uses fetch to call your backend. Here's the core pattern AI will generate — a function that sends a new entry and reads the response. Run it to see how a request payload and a parsed response look.
async function addEntry(entry) {
// In a real app this URL hits your backend; here we just simulate it
const fakeServer = (data) => ({ id: 1, ...data, saved: true });
const payload = JSON.stringify(entry);
console.log("Sending to /api/entries:", payload);
const response = fakeServer(JSON.parse(payload));
console.log("Server responded:", response);
return response;
}
addEntry({ client: "Acme", hours: 2, date: "2026-06-10" });Test the Connection End to End
Wiring isn't done until you've watched data flow both ways. Run the app, submit the form, and confirm the new entry appears in the list — that proves the frontend reached the backend and got a response.
If nothing happens, AI is great at diagnosing the gap when you describe exactly what you saw.
I built the form and the /api/entries endpoints. When I submit the form, nothing appears in the list, but I see no error on screen.
Help me debug the connection between frontend and backend. Tell me:
- what to check in the browser's Network tab
- what console.logs to add
- the most common reasons a fetch silently failsSame-Project vs. Separate Servers
You'll hear two setups. In a full-stack framework like Next.js, the frontend and backend live in one project and deploy together — simplest for beginners. Alternatively, you can run a separate backend (its own server) and a separate frontend.
For vibe coding, staying in one project avoids cross-server headaches like CORS. Ask AI which fits your goals.
Compare two setups for my freelancer hours app:
1. One Next.js project containing both frontend and API routes
2. A separate backend server plus a separate frontend
For a beginner who wants to ship fast on Vercel, which do you recommend and why? Mention any extra complexity like CORS that I'd avoid with the simpler option.Handle Errors Gracefully
Real networks fail. A request can time out, the server can return an error, or the data can be malformed. A good app shows the user a friendly message instead of breaking silently.
Ask AI to add error handling to both sides so failures are visible and recoverable.
Add robust error handling to my time-entry feature.
Frontend: if the POST fails, show a friendly inline error and let the user retry.
Backend: validate input and return a clear error message with the right status code (e.g. 400 for bad input).
Show me the updated code and explain what each error case covers.Keep Frontend and Backend in Agreement
The #1 cause of broken full-stack apps is the two halves disagreeing on the data shape — the frontend sends hrs but the backend expects hours.
Keep one source of truth for your data shape (note it in PROJECT.md), and when you change one side, tell the AI to update the other. Consistency is what makes the wiring hold.
I'm changing the time entry shape from { client, hours, date } to { clientId, minutes, date, note }.
Update BOTH the /api/entries endpoint and the frontend form/list to use the new shape consistently. Update PROJECT.md too. Show me a checklist of every place that had to change.You Built a Working Loop
You now have a real round-trip: a user fills a form, the frontend fetches your backend endpoint, the backend processes and responds, and the screen updates. That loop is the heartbeat of every full-stack app.
Right now data only lives in memory and vanishes on restart. Next, we'll make it permanent with a real database.
Quick Check
Make sure the frontend/backend connection is clear.
Recap: Wiring the Two Halves
You connected frontend and backend by prompting AI:
- They communicate via HTTP requests and responses (JSON)
- The backend exposes API endpoints; the frontend calls them with
fetch - Build and test one endpoint at a time
- Add error handling on both sides
- Keep the data shape consistent across frontend and backend
Next: store your data for real with a database so it survives a restart.
常见问题解答
「前端与后端协同」课时是免费的吗?
是的 — 「前端与后端协同」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Vibe Coding 课程的其余内容,请升级到 CoddyKit PRO。 Vibe Coding 课程共包含 4 节课。
「前端与后端协同」这节课中我会学到什么?
连接屏幕与服务器 你通过在浏览器中直接运行的动手代码来练习 Vibe Coding,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Vibe Coding 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Vibe Coding 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「前端与后端协同」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Vibe Coding 课中编写并运行代码吗?
能。每节 Vibe Coding 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用人工智能规划应用
- 前端与后端协同
- 添加数据库
- 用户账户与登录