在Express中路由文件夹 [英] Routes folder in Express

查看:84
本文介绍了在Express中路由文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建Express应用程序时,您将获得路径文件夹。所有路由都在app.js文件中注册。然而,发生的事情的逻辑位于routes文件夹的文件中。这是其他框架中控制器文件夹的同义词吗?这是您应该添加请求/响应逻辑的位置吗?

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?

推荐答案

是的,与控制器文件夹有点相同。 IMO,你最好使用不同的文件,就像使用另一种语言的控制器一样,因为当应用程序越来越大时,当所有的请求/响应逻辑都在同一个文件中时,很难理解代码。

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.

示例:

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

这篇关于在Express中路由文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆