← 第 3 关 – 大师

第 8/10 课 ⏱ 40 分钟 高级版

用 Express 搭小服务器

用 Node.js 和 Express 建自己的服务器。第一个 API 回应第一个请求。

跟我看:搭建服务器

Express 是 Node.js 里建服务器最流行的包——几行搞定。服务器是 单独项目,和 React 应用分开(记住:前端和后端是两半)。在终端:

cd Desktop
mkdir my-server
cd my-server
npm init -y
npm install express

在 VS Code 打开文件夹,创建 server.js

const express = require("express");
const app = express();

// When someone sends a GET to /api/hello, respond
app.get("/api/hello", (request, response) => {
  response.json({ message: "Hi! This is your own server. 🎉" });
});

app.listen(3900, () => {
  console.log("Server running at http://localhost:3900");
});

运行:

node server.js

浏览器打开 http://localhost:3900/api/hello。看到 JSON 响应了吗?你刚刚建了服务器。 没魔法——10 行。

代码里发生什么:

Ctrl+C 停服务器。注意:每次改代码要停再启——服务器不是 Vite,不会自己刷新。

跟我看:带数据的服务器

服务器通常分发数据。在 listen 上面加第二个 endpoint:

const results = [
  { opponent: "Lakeside", score: "3:1", home: true },
  { opponent: "Northgate", score: "2:2", home: false },
  { opponent: "Elmwood", score: "4:0", home: true },
];

app.get("/api/results", (request, response) => {
  response.json(results);
});

重启服务器,打开 http://localhost:3900/api/results——你的数据,通过 API 提供。每个大网站都这样(只是用数据库代替数组)。

轮到你了 💪

  1. 按指南让服务器跑起来。
  2. 加带你项目数据的 endpoint:🏫 /api/menu(一周餐食数组)· 🙋 /api/favorites(最爱游戏/书)· 🌍 /api/trips(旅行列表)· ⚽ /api/results(比赛结果)。
  3. 加好玩的 endpoint /api/random,每次返回不同消息:
const messages = ["We're winning today!", "Practice at 5 PM!", "Let's go, Eagles!"];

app.get("/api/random", (request, response) => {
  const random = messages[Math.floor(Math.random() * messages.length)];
  response.json({ message: random });
});
  1. 在浏览器试所有 endpoint——然后用上一课学的 fetch() 从控制台调一个。
⚠️

“Cannot GET /api/…” 表示 endpoint 不存在——检查地址拼写和改代码后是否重启了服务器。“EADDRINUSE” 表示 3900 端口被占用——可能另一个终端里旧服务器还在跑;找到并 Ctrl+C 停掉。

检查一下: 服务器在 3900 端口跑,多个 endpoint 用你自己的 JSON 数据回应。前端会了,后端开始了——只剩连起来。下一课用留言板正好做这个。

这堂课你要记住