在軟件架構(gòu)中,Controller 是一種關(guān)鍵的設(shè)計模式,主要用于處理用戶輸入并協(xié)調(diào)模型和視圖之間的交互。在MVC(模型-視圖-控制器)架構(gòu)中,Controller 充當中介者,將用戶的請求傳遞給模型進行數(shù)據(jù)處理,然后將結(jié)果返回給視圖進行顯示。
在開始之前,我們需要有基本的文件夾結(jié)構(gòu),例如:
/myapp
/controllers
/models
/views
app.js
在controllers文件夾中創(chuàng)建一個新的Controller文件,比如 UserController.js。
const UserModel = require('../models/UserModel');
class UserController {
static async getUser(req, res) {
const userId = req.params.id;
const user = await UserModel.findById(userId);
res.json(user);
}
}
module.exports = UserController;
在主應用文件 app.js 中導入Controller,并設(shè)置路由:
const express = require('express');
const UserController = require('./controllers/UserController');
const app = express();
const port = 3000;
app.get('/user/:id', UserController.getUser);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
啟動服務器后,可以通過瀏覽器或API工具(如Postman)訪問URL:
http://localhost:3000/user/1
這將調(diào)用 UserController.getUser 方法并返回用戶信息。