Routes folder in Express

狂风中的少年 提交于 2020-01-02 00:52:16

问题


When you create an Express application you get a routes folder. All routes are registered in the app.js file. However the logic on what happens is located in the files of the routes folder. Is this a synonym for controller folders in other frameworks? Is this the location of where you should add the request/response logic?


回答1:


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.

Example :

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 :

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"});
};


来源:https://stackoverflow.com/questions/14160025/routes-folder-in-express

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