繁体   English   中英

如何在Node.js / Express中组织路由依赖关系

[英]How to organize route dependencies in Node.js / Express

我知道如何将路由导出到index.js文件,但是我遇到的问题是我不了解如何正确引用这些外部路由依赖项,而又没有将它们粘贴到文件的顶部。

换句话说,如果我具有该程序的入口点(称为index.js),并且具有依赖项列表:

index.js

const Sequelize = require("sequelize");
const connection = new Sequelize("jsfsa", "root", "password");
const bcrypt = require("bcryptjs");
const salt = bcrypt.genSaltSync(10);
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
const session = require('client-sessions');
const expressHbs = require('express-handlebars');
const csrf = require("csurf");

// .....etc....

然后我有一个在外部文件中引用的路由(可以说是发布路由):

路线/login.js

exports.submitLogin = (req, res) => {
   // do a bunch of stuff that requires the dependencies referenced in index.js
}

我无法弄清楚如何仅在路由文件中放置所需的模块“ requires”而不引用任何依赖项。

路线/login.js

const Sequelize = require("sequelize");
const connection = new Sequelize("jsfsa", "root", "password");
const bcrypt = require("bcryptjs");
const salt = bcrypt.genSaltSync(10);
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
const session = require('client-sessions');
const expressHbs = require('express-handlebars');
const csrf = require("csurf");

// .....etc....




exports.submitLogin = (req, res) => {
   // do a bunch of stuff that requires the dependencies referenced in index.js
}

我想相信有一种方法可以将所有模块引用放置在文件my_dependencies.js ,然后使用像函数调用一样简单的一行代码简单地引用应用程序中所有其他页面的整个文件。

好奇是否可行。

我尝试过在线阅读如何处理此问题,这一切使我感到困惑。

我这样做的方法是将所需的依赖变量直接传递给处理该特定路由的函数。 在您的情况下:

index.js (或定义路由的任何地方)

app.post('/someRoute', require('routes/login').submitLogin(dependency1, dependency2));
//If you are using express.Router() to handle routes/sub-routes,
//then this line could be different

路线/login.js

exports.submitLogin = function(dependency1, dependency2)
    return function(req, res){
       // do a bunch of stuff that requires the dependencies referenced in index.js
    }
}

当然,在这种情况下,我会基于这样一个事实,即您不会在每个函数中使用每个依赖 ,这会破坏它的意义。
这也使我可以将其他上下文或状态相关的变量传递给我的路由处理程序。


还有一种做法是将依赖变量简单地放在app变量中,例如:

app.dependency=someobject;

假设这可以使您使用req.app.dependency1访问依赖req.app.dependency1 ,但不建议这种做法,因为它可能会干扰app对象的现有子项。

暂无
暂无

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

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