目錄
Node.js 路由 - 初識 Express 中的路由
1. 什么是路由?
2. 安裝 Express
3. 創建 server.js
4. 運行服務器
5. 測試路由
5.1 訪問主頁
5.2 訪問用戶路由
5.3 發送 POST 請求
6. 結語
1. 什么是路由?
路由(Routing)是指根據不同的 URL 地址,服務器返回不同的內容。在 Express 中,我們可以使用 app.get()
、app.post()
等方法定義路由。
2. 安裝 Express
mkdir express-routing && cd express-routing # 創建項目目錄
npm init -y # 初始化項目
npm install express # 安裝 Express
3. 創建 server.js
文件名:server.js(JavaScript 代碼)
// server.js
const express = require('express'); // 引入 Express
const app = express(); // 創建應用
const port = 3000; // 服務器端口// 主頁路由
app.get('/', (req, res) => {res.send('歡迎來到 Express 主頁!');
});// 用戶路由(GET 請求)
app.get('/user/:name', (req, res) => {const name = req.params.name; // 獲取 URL 參數res.send(`你好,${name}!`);
});// 提交數據路由(POST 請求)
app.use(express.json()); // 解析 JSON 請求體
app.post('/submit', (req, res) => {const { username, age } = req.body; // 獲取請求體數據res.json({ message: '數據提交成功', user: { username, age } });
});// 啟動服務器
app.listen(port, () => {console.log(`服務器運行在 http://localhost:${port}`);
});
4. 運行服務器
執行命令:
node server.js
5. 測試路由
5.1 訪問主頁
瀏覽器打開 http://localhost:3000/
,頁面顯示:
歡迎來到 Express 主頁!
5.2 訪問用戶路由
瀏覽器訪問 http://localhost:3000/user/Tom
,頁面顯示:
你好,Tom!
5.3 發送 POST 請求
使用 Postman 或 curl
發送請求:
curl -X POST http://localhost:3000/submit -H "Content-Type: application/json" -d '{"username": "Alice", "age": 25}'
服務器返回 JSON 響應:
{"message": "數據提交成功","user": {"username": "Alice","age": 25}
}
6. 結語
本文介紹了 Express 路由 的基本用法,包括 GET 和 POST 請求,以及如何獲取 URL 參數和請求體數據。希望這篇教程能幫助你快速上手 Express 路由!🚀