简体   繁体   English

在Express中路由文件夹

[英]Routes folder in Express

When you create an Express application you get a routes folder. 创建Express应用程序时,您将获得路径文件夹。 All routes are registered in the app.js file. 所有路由都在app.js文件中注册。 However the logic on what happens is located in the files of the routes folder. 然而,发生的事情的逻辑位于routes文件夹的文件中。 Is this a synonym for controller folders in other frameworks? 这是其他框架中控制器文件夹的同义词吗? Is this the location of where you should add the request/response logic? 这是您应该添加请求/响应逻辑的位置吗?

Yes, is kind of the same thing as a controller folder. 是的,与控制器文件夹有点相同。 IMO, you better use different files as you would with controllers in another language because when the application is getting bigger it's hard to understand the code when all the request/response logic is in the same file. IMO,您最好使用不同的文件,就像使用其他语言的控制器一样,因为当应用程序变得越来越大时,当所有请求/响应逻辑位于同一文件中时,很难理解代码。

Example : 示例:

app.js : app.js

var express = require('express'),
    employees = require('./routes/employee');

var app = express();

app.get('/employees', employees.findAll);
app.get('/employees/:id', employees.findById);

app.listen(80);

routes/employee.js : routes / employee.js

exports.findAll = function(req, res) {
    res.send([{name:'name1'}, {name:'name2'}, {name:'name3'}]);
};

exports.findById = function(req, res) {
    res.send({id:req.params.id, name: "The Name", description: "description"});
};

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

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