How to write clean, modular express.js applications

寵の児 提交于 2020-01-25 06:13:45

问题


Pretty much since forever, I've stayed away from NodeJS backend development for one reason and one reason only: Almost all Express projects I've started or I've been forced to maintain end up being a huge mess where the entire website is run on a single script that's +/- 5000 lines long.

The the following example from the ExpressJS hello world page, in this form I'd end up adding more and more routes to app leading to a huge mess of code.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
    res.send('Hello World!');
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

What I can't seem to find, is how I could take a large express website, and turn it into a modular application where routes are small, re-usable and easily testable. If anyone has any idea of how to do this it would be greatly appreciated.


回答1:


I generally use 1 file per route and put all my routing files in a routes folder and leverage the Router available in express.

A route file could look like this:

var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
    res.send('Hello World!');
});

module.exports = router;

Then in the app file, simply add:

var example = require('./routes/example');
app.use('/', example);

The routes in the routing file are relative to the route you declare in app.use.



来源:https://stackoverflow.com/questions/38739856/how-to-write-clean-modular-express-js-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!