简体   繁体   English

如何在Node.js和Express中更好地组织路线?

[英]How can I organize my routes better in nodejs & express?

My WebAPI code at the moment is pretty modular I would say. 我想说,目前我的WebAPI代码是模块化的。 But I would like it to be even more. 但我希望它能更多。

I have this server.js file that has all the routes, and I would like to split them into separate controllers. 我有包含所有路由的server.js文件,我想将它们拆分为单独的控制器。 Any idea on how to do that? 关于如何做到这一点的任何想法? Here's an example: 这是一个例子:

app.get('/users/me', authenticate, (req, res) => {
    res.send(req.user);
});

I have a bunch of these routes in my server.js file. 我的server.js文件中有一堆这样的路由。 How would I go about creating a user-routes.js file with my user routes there? 我将如何使用用户路由在那里创建user-routes.js文件? Also for all the other collections' routes I have set up. 同样,对于所有其他集合的路线,我都已设置好。

app.post('/firm', authenticate, (req, res) => {
    var firm = new Firm({
        name: req.body.name,
        number: req.body.number,
        _creator: req.user._id
    });

    Firm.findOne({
        number: req.body.number,
        _creator: req.user._id
    }).then(firmFound => {
        if (firmFound) {
            return res.status(400).send({
                message: 'Firm with that name or number already exists.'
            })
        }
        firm.save().then((firm) => {
            res.send(firm);
        }, (e) => {
            res.status(400).send(e);
        });

    });
});

On a subfile, eg users.js you can define a new Router : 在一个子文件,例如users.js您可以定义一个新的Router

const users = Express.Router();

users.get("/me", () => "whatever");

module.exports = users;

That applies to all your subroutes and even subsubroutes. 这适用于您的所有子路由,甚至是子子路由。 Then on the higher instance you just need to mount that subroutes under their path (server.js for example): 然后在更高的实例上,您只需要将该子路由安装在其路径下(例如,server.js):

app.use("/users/", require("users.js"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM