2016-06-14 5 views
0

私はindex.jsファイルにルートをエクスポートする方法を理解していますが、問題は、それらの外部ルート依存関係を貼り付けることなく適切に参照する方法がわかりませんファイルの先頭言い換えればNode.js/Expressでルート依存関係を整理する方法

私は(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.... 

、その後、I

ルート/ login.js

:外部ファイルで参照されているルートを(ポストルートを言うことができます)持っています
exports.submitLogin = (req, res) => { 
    // do a bunch of stuff that requires the dependencies referenced in index.js 
} 

ルートファイルに必要なモジュールを "必須"にするだけで、依存関係をどのように参照するのか分かりません。

ルート/ 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内のすべてのモジュール参照を配置する方法があると考えていると、単に私の中のすべての他のページからファイル全体を参照したいですアプリケーションは、関数呼び出しのような単純なコード行を使用します。

これが可能かどうか不思議です。

私はオンラインでこの問題に対処する方法を試しましたが、すべてが私にとって非常に混乱しています。

答えて

0

私が行う方法は、その特定のルートを処理する関数に直接必要な依存変数を渡すことです。あなたの場合:

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 
    } 
} 

、この実際にはIあなたがすべての機能にという単一の依存関係を使用するつもりはないという事実を踏まえて、その点を打破しています。
これにより、他のコンテキストまたは状態依存変数をルートハンドラに渡すこともできます。


のように単にapp変数にあなたの依存関係変数を入れての練習は、もあります。これは仮にあなたがreq.app.dependency1を使用して、依存関係にアクセスできますが、この練習は次のように推奨されません

app.dependency=someobject; 

appオブジェクトの既存の子を妨害する可能性があります。

関連する問題