可衡量的指標才能讓老板一眼看出 ROI。
# 1. 創建項目
mkdir node-ts-api && cd node-ts-api
npm init -y
# 2. 安裝依賴
npm install express
npm install -D typescript ts-node nodemon @types/node @types/express
# 3. 初始化 TypeScript
npx tsc --init
# 4. 腳本命令
npm pkg set scripts.start="ts-node src/index.ts"
npm pkg set scripts.dev="nodemon src/index.ts"
npm pkg set scripts.build="tsc"
npm pkg set scripts.serve="node dist/index.js"
// src/index.ts
import express, { Request, Response } from 'express';
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.get("/", (req: Request, res: Response) => {
res.json({ message: "Node.js + TypeScript API 運行中!" });
});
app.listen(PORT, () => console.log(Server on port ${PORT}));
// src/routes/bookRoutes.ts
import { Router, Request, Response } from 'express';
const router = Router();
interface Book {
id: number;
title: string;
author: string;
}
let books: Book[] = [
{ id: 1, title: "1984", author: "George Orwell" },
{ id: 2, title: "Brave New World", author: "Aldous Huxley" }
];
router.get("/books", (req: Request, res: Response) => res.json(books));
router.get("/books/:id", (req: Request, res: Response) => {
const book = books.find(b => b.id === parseInt(req.params.id));
return book ? res.json(book) : res.status(404).json({ message: "Book not found" });
});
router.post("/books", (req: Request, res: Response) => {
const newBook: Book = { id: books.length + 1, ...req.body };
books.push(newBook);
res.status(201).json(newBook);
});
router.put("/books/:id", (req: Request, res: Response) => {
const idx = books.findIndex(b => b.id === parseInt(req.params.id));
if (idx === -1) return res.status(404).json({ message: "Book not found" });
books[idx] = { ...books[idx], ...req.body };
res.json(books[idx]);
});
router.delete("/books/:id", (req: Request, res: Response) => {
const idx = books.findIndex(b => b.id === parseInt(req.params.id));
if (idx === -1) return res.status(404).json({ message: "Book not found" });
books.splice(idx, 1);
res.status(204).send();
});
export default router;
// src/index.ts
import express from 'express';
import bookRoutes from './routes/bookRoutes';
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use("/api", bookRoutes);
app.listen(PORT, () => console.log(Server on port ${PORT}));
使用 Postman 或 cURL 快速驗證:
# 獲取全部書籍
curl http://localhost:3000/api/books
# 創建新書
curl -X POST http://localhost:3000/api/books \
-H "Content-Type: application/json" \
-d '{"title":"The Hobbit","author":"J.R.R. Tolkien"}'
npm run build # tsc → dist/
npm run serve # node dist/index.js
讓「代碼優化」把同步改 asyncio + 連接池,并發 1 k QPS,延遲立降 60 % ??
| 挑戰 | 逃生術 |
|---|---|
| 類型漂移 | 開啟 strict: true + ESLint 插件 |
| 熱更新失效 | nodemon 監聽 src/**/*.ts,勿忘 ts-node 注冊 |
| 限流 1K QPS | 本地令牌桶 + 指數退避;高峰申請提升配額 |
| 密鑰泄露 | 用中間件代理,前端只拿短期 JWT,30 min 自動刷新 |
X-Rate-Limit-Remaining,提前告警 strictNullChecks,運行時出現 undefined |requestId,出錯無法追蹤 |從環境初始化、類型定義到并發優化,一站式模板讓團隊在“后端馬拉松”中穩占先機;再用「代碼文檔生成器」自動生成 SDK 文檔,外部開發者 5 分鐘就能上手。
注意:Node.js 版本與依賴會隨社區更新,上線前請查閱官方 Release Note。
原文鏈接: https://medium.com/@holasoymalva/how-to-build-a-rest-api-with-node-js-and-typescript-3491ddd19f95