目录

ExpressJS - 最佳实践( Best Practices)

与具有定义的处理方式,文件结构等的Django和Rails不同,Express不遵循定义的方式。 这意味着您可以按照自己喜欢的方式构建应用程序。 但是随着应用程序的大小增加,如果它没有明确定义的结构,则很难维护它。 在本章中,我们将介绍常用的目录结构和关注点分离,以构建我们的应用程序。

首先,我们将讨论创建节点和Express应用程序的最佳实践。

  • 始终使用npm init开始一个节点项目。

  • 始终使用--save--save-dev安装依赖项。 这将确保如果您移动到其他平台,则可以运行npm install来安装所有依赖项。

  • 坚持使用小写文件名和camelCase变量。 如果查看任何npm模块,它以小写字母命名并用短划线分隔。 每当您需要这些模块时,请使用camelCase。

  • 不要将node_modules推送到您的存储库。 相反,npm会在开发机器上安装所有内容。

  • 使用config文件存储变量

  • 将路由分组并隔离到自己的文件。 例如,在我们在REST API页面中看到的电影示例中进行CRUD操作。

目录结构

现在让我们讨论Express的目录结构。

Websites

Express没有用于创建应用程序的社区定义结构。 以下是网站的主要项目结构。

test-project/
   node_modules/
   config/
      db.js                //Database connection and configuration
      credentials.js       //Passwords/API keys for external services used by your app
      config.js            //Other environment variables
   models/                 //For mongoose schemas
      users.js
      things.js
   routes/                 //All routes for different entities in different files 
      users.js
      things.js
   views/
      index.pug
      404.pug
        ...
   public/                 //All static content being served
      images/
      css/
      javascript/
   app.js
   routes.js               //Require all routes in this and then require this file in 
   app.js 
   package.json

还有其他方法可以使用Express构建网站。 您可以使用MVC设计模式构建网站。 有关更多信息,请访问以下链接。

https://code.tutsplus.com/tutorials/build-a-complete-mvc-website-with-expressjs--net-34168

和,

https://www.terlici.com/2014/08/25/best-practices-express-structure.html

RESTful API

API更易于设计; 他们不需要public或views目录。 使用以下结构构建API -

test-project/
   node_modules/
   config/
      db.js                //Database connection and configuration
      credentials.js       //Passwords/API keys for external services used by your app
   models/                 //For mongoose schemas
      users.js
      things.js
   routes/                 //All routes for different entities in different files 
      users.js
      things.js
   app.js
   routes.js               //Require all routes in this and then require this file in 
   app.js 
   package.json

您还可以使用自动生成器来获得类似的结构。

↑回到顶部↑
WIKI教程 @2018