当前位置: 首页 > news >正文

Express MVC

1. 安装依赖

npm init -y
npm install express
npm install --save-dev typescript ts-node ejs @types/node @types/express
tsc --init

2. 项目目录结构如下,没有的手动创建

/my-app
	/src
		/models
			user.ts
		/views
			index.ejs
            userList.ejs
		/controllers
			userController.ts
		/routes
			userRoutes.ts
		/public
			/css
			/js
		app.ts
	tsconfig.json

3. TypeScript 配置 (tsconfig.json)

{
    "compilerOptions": {
        "target": "ES6",
        "module": "commonjs",
        "outDir": "./dist",
        "rootDir": "./src",
        "esModuleInterop": true, // 兼容 esm 和 commonjs
        "forceConsistentCasingInFileNames": true, // 导入时大小写必须一致
        "strict": true // 启用 ts 的严格类型检查
    },
    "include": [
        "src/**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}

4. 代码实现

app.ts (主应用文件)

import express from 'express';
import path from 'path';
import userRoutes from './routes/userRoutes';

const app = express();

// 设置视图引擎为 EJS,参数名称固定写法,不可以随意更改
app.set('view engine', 'ejs');

// 设置视图文件夹位置
app.set('views', path.join(__dirname, 'views'));

// 设置静态文件夹
app.use(express.static(path.join(__dirname, 'public')));

// 解析请求体
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// 使用路由
app.use('/users', userRoutes);

// 根路由
app.get('/', (req, res) => {
    res.render('index', { title: 'Express + TypeScript MVC' });
});

// 启动服务器
const port = 3000;
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

models/user.ts (模型)

export interface User {
    id: number;
    name: string;
    email: string;
}

export const getUsers = (): User[] => {
    return [
        { id: 1, name: 'John Doe', email: 'john@example.com' },
        { id: 2, name: 'Jane Doe', email: 'jane@example.com' },
    ];
};

controllers/userController.ts (控制器)

import { Request, Response } from 'express';
import { getUsers } from '../models/user';

export const getUserList = (req: Request, res: Response) => {
    const users = getUsers();
    res.render('userList', { users });
};

routes/userRoutes.ts (路由)

import express from 'express';
import { getUserList } from '../controllers/userController';

const router = express.Router();

// 用户列表路由
router.get('/', getUserList);

export default router;

views/index.ejs (视图)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <%= title %>
    </title>
</head>

<body>
    <h1>Welcome to Express + TypeScript MVC!</h1>
    <a href="/users">Go to Users</a>
</body>

</html>

views/userList.ejs (显示用户列表的视图)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User List</title>
</head>

<body>
    <h1>User List</h1>
    <ul>
        <% users.forEach(user=> { %>
            <li>
                <%= user.name %> - <%= user.email %>
            </li>
        <% }) %>
    </ul>
    <a href="/">Back to Home</a>
</body>

</html>

5. 运行项目

在 package.json 中设置启动脚本:

"scripts": {
    "start": "ts-node src/app.ts"
},

启动应用

npm run start

6. 访问应用

相关文章:

  • Spring基础05
  • git 鼓励频繁提交commit early, commit often,用好分支,多用分支
  • 【SpringBoot+Vue】博客项目开发二:用户登录注册模块
  • 乡村研学旅行小程序(论文源码调试讲解)
  • 行为型模式 - 观察者模式 (Publish/Subscribe)
  • 【华三】从零开始掌握SR技术:原理、架构与应用全解析
  • golang介绍,特点,项目结构,基本变量类型与声明介绍(数组,切片,映射),控制流语句介绍(条件,循环,switch case)
  • 开发一个o2o(线上到线下)商城需要具备以下条件
  • 快速入手-搭建Flask框架封装mysql并结合业务实际情况使用
  • 【MySQL】MySQL用户管理
  • Flask笔记
  • 在 Element Plus 的 <el-select> 组件中,如果需要将 <el-option> 的默认值设置为 null。 用于枚举传值
  • JavaScript 注释
  • LeetCode 解题思路 6(Hot 100)
  • Nginx 配置与常用命令速查手册
  • 神经网络|(十一)|神经元和神经网络
  • Hive-01之数仓、架构、数据类型、DDL、内外部表
  • 纯c#字体处理库(FontParser) -- 轻量、极速、跨平台、具有字体子集化功能
  • 开源程序wordpress在海外品牌推广中的重要作用
  • Qt空项目代码解释
  • 网站后台管理的超级链接怎么做/哈尔滨网站优化流程
  • 哪个网站做h5号/海南百度推广电话
  • 网站高并发前端怎么做/百度客服人工电话多少
  • 云南app开发制作/郑州搜索引擎优化公司
  • 留言板网站模板/it菜鸡网seo
  • 为什么网站有不同的扩展名/百度搜索风云榜小说排行榜