如何在Node.js中构建后端代码 (Express.js)

使用 Express.js 开发 Node.js 应用程序时,有效地构建代码库对于可维护性、可伸缩性和易于协作至关重要。组织良好的项目结构允许您管理复杂性,从而更轻松地导航和理解代码。在此博客中,我们将探讨 Express.js 应用程序的典型文件夹结构,并解释每个目录和文件的用途。

项目结构概述

下面是Express.js应用程序的通用文件夹结构:

📁
├── 📄 app.js
├── 📁 bin
├── 📁 config
├── 📁 controllers
│   ├── 📄 customer.js
│   ├── 📄 product.js
│   └── ...
├── 📁 middleware
│   ├── 📄 auth.js
│   ├── 📄 logger.js
│   └── ...
├── 📁 models
│   ├── 📄 customer.js
│   ├── 📄 product.js
│   └── ...
├── 📁 routes
│   ├── 📄 api.js
│   ├── 📄 auth.js
│   └── ...
├── 📁 public
│   ├── 📁 css
│   ├── 📁 js
│   ├── 📁 images
│   └── ...
├── 📁 views
│   ├── 📄 index.ejs
│   ├── 📄 product.ejs
│   └── ...
├── 📁 tests
│   ├── 📁 unit
│   ├── 📁 integration
│   ├── 📁 e2e
│   └── ...
├── 📁 utils
│   ├── 📄 validation.js
│   ├── 📄 helpers.js
│   └── ...
└── 📁 node_modules

每个目录和文件的说明

app.js

该文件是应用程序的入口点。您可以在其中初始化 Express 应用程序、设置中间件、定义路由和启动服务器。将其视为 Web 应用程序的控制中心。app.js

const express = require('express');
const app = express();
const config = require('./config');
const routes = require('./routes');

// Middleware setup
app.use(express.json());

// Routes setup
app.use('/api', routes);

// Start server
const PORT = config.port || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

module.exports = app;
bin

该目录通常包含用于启动 Web 服务器的脚本。这些脚本可用于设置环境变量或管理不同的环境(例如,开发、生产)。bin

示例:bin/www

#!/usr/bin/env node

const app = require('../app');
const debug = require('debug')('your-app:server');
const http = require('http');

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

const server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

function normalizePort(val) {
  const port = parseInt(val, 10);
  if (isNaN(port)) return val;
  if (port >= 0) return port;
  return false;
}

function onError(error) {
  if (error.syscall !== 'listen') throw error;
  const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

function onListening() {
  const addr = server.address();
  const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
  debug('Listening on ' + bind);
}
config

该目录包含应用程序的配置文件,例如数据库连接、服务器设置和环境变量。config

示例:config/index.js

module.exports = {
  port: process.env.PORT || 3000,
  db: {
    host: 'localhost',
    port: 27017,
    name: 'mydatabase'
  }
};

 controllers

控制器包含用于处理传入请求和生成响应的逻辑。目录中的每个文件通常对应于应用程序的不同部分(例如,客户、产品)。controllers

示例:controllers/customer.js

const Customer = require('../models/customer');

exports.getAllCustomers = async (req, res) => {
  try {
    const customers = await Customer.find();
    res.json(customers);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
middleware

中间件函数用于在请求到达控制器之前对其进行处理。它们可以处理身份验证、日志记录和请求验证等任务。

示例:中间件/auth.js

module.exports = (req, res, next) => {
  const token = req.header('Authorization');
  if (!token) return res.status(401).json({ message: 'Access Denied' });

  try {
    const verified = jwt.verify(token, process.env.JWT_SECRET);
    req.user = verified;
    next();
  } catch (err) {
    res.status(400).json({ message: 'Invalid Token' });
  }
};
models

模型定义数据的结构并处理与数据库的交互。每个模型文件通常对应于不同的数据实体(例如,客户、产品)。

示例:models/customer.js

const mongoose = require('mongoose');

const customerSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Customer', customerSchema);
routes

路由定义应用程序不同部分的路径,并将它们映射到相应的控制器。

示例:routes/api.js

const express = require('express');
const router = express.Router();
const customerController = require('../controllers/customer');

router.get('/customers', customerController.getAllCustomers);

module.exports = router;

 public

该目录包含直接提供给客户端的静态文件,如 CSS、JavaScript 和图像。public

示例:目录结构

public/
├── css/
├── js/
├── images/
views

视图是为客户端呈现 HTML 的模板。使用 EJS、Pug 或 Handlebars 等模板引擎,您可以生成动态 HTML。

示例:views/index.ejs

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
  <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
  <h1>Welcome to My App</h1>
  <div id="content">
    <%- content %>
  </div>
</body>
</html>

tests

该目录包含测试文件,以确保应用程序正常工作。测试通常分为单元测试、集成测试和端到端 (e2e) 测试。tests

示例:目录结构

tests/
├── unit/
├── integration/
├── e2e/
utils

实用程序函数和帮助程序模块存储在目录中。这些函数执行在整个应用程序中使用的常见任务,如验证和格式设置。utils

示例:utils/validation.js

exports.isEmailValid = (email) => {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(String(email).toLowerCase());
};
node_modules

该目录包含项目所需的所有依赖项。此目录由 npm(或 yarn)管理,包括从 npm 注册表安装的包。node_modules

结论

使用 Express.js 的结构良好的 Node.js 应用程序可增强可维护性、可伸缩性和协作性。结构中的每个目录和文件都有特定的用途,从处理配置和定义路由到管理中间件和呈现视图。通过有效地组织代码库,您可以轻松构建强大且可扩展的应用程序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值