program story

Express : 앱 인스턴스를 다른 파일의 경로로 전달하는 방법은 무엇입니까?

inputbox 2020. 8. 21. 07:42
반응형

Express : 앱 인스턴스를 다른 파일의 경로로 전달하는 방법은 무엇입니까?


내 경로를 다른 파일로 나누고 싶습니다. 한 파일에는 모든 경로가 포함되고 다른 파일에는 해당 작업이 포함됩니다. 현재이를 달성 할 수있는 솔루션이 있지만 작업에서 액세스 할 수 있도록 앱 인스턴스를 전역으로 만들어야합니다. 내 현재 설정은 다음과 같습니다.

app.js :

var express   = require('express');
var app       = express.createServer();
var routes    = require('./routes');

var controllers = require('./controllers');
routes.setup(app, controllers);

app.listen(3000, function() {
  console.log('Application is listening on port 3000');
});

route.js :

exports.setup = function(app, controllers) {

  app.get('/', controllers.index);
  app.get('/posts', controllers.posts.index);
  app.get('/posts/:post', controllers.posts.show);
  // etc.

};

controllers / index.js :

exports.posts = require('./posts');

exports.index = function(req, res) {
  // code
};

controllers / posts.js :

exports.index = function(req, res) {
  // code
};

exports.show = function(req, res) {
  // code
};

그러나이 설정에는 큰 문제가 있습니다. 작업 (controllers / *. js)에 전달해야하는 데이터베이스 및 앱 인스턴스가 있습니다. 내가 생각할 수있는 유일한 옵션은 두 변수를 모두 전역으로 만드는 것인데, 이는 실제로 해결책이 아닙니다. 경로가 많고 중앙에 위치하기를 원하기 때문에 작업에서 경로를 분리하고 싶습니다.

작업에 변수를 전달하고 경로에서 작업을 분리하는 가장 좋은 방법은 무엇입니까?


Node.js는 순환 종속성을 지원합니다.
require ( './ routes') (app) 대신 순환 종속성을 사용하면 많은 코드가 정리되고 각 모듈이로드 파일에 덜 상호 의존하게됩니다.


app.js

var app = module.exports = express(); //now app.js can be required to bring app into any file

//some app/middleware setup, etc, including 
app.use(app.router);

require('./routes'); //module.exports must be defined before this line


route / index.js

var app = require('../app');

app.get('/', function(req, res, next) {
  res.render('index');
});

//require in some other route files...each of which requires app independently
require('./user');
require('./blog');


----- 2014 년 4 월 업데이트 -----
Express 4.0은 express.router () 메서드를 추가하여 경로를 정의하는 사용 사례를 수정했습니다!
문서 -http : //expressjs.com/4x/api.html#router

새 생성기의 예 :
경로 작성 :
https://github.com/expressjs/generator/blob/master/templates/js/routes/index.js
앱에 추가 / 이름 간격 지정 : https://github.com /expressjs/generator/blob/master/templates/js/app.js#L24

There are still usecases for accessing app from other resources, so circular dependencies are still a valid solution.


Use req.app, req.app.get('somekey')

The application variable created by calling express() is set on the request and response objects.

See: https://github.com/visionmedia/express/blob/76147c78a15904d4e4e469095a29d1bec9775ab6/lib/express.js#L34-L35


Like I said in the comments, you can use a function as module.exports. A function is also an object, so you don't have to change your syntax.

app.js

var controllers = require('./controllers')({app: app});

controllers.js

module.exports = function(params)
{
    return require('controllers/index')(params);
}

controllers/index.js

function controllers(params)
{
  var app = params.app;

  controllers.posts = require('./posts');

  controllers.index = function(req, res) {
    // code
  };
}

module.exports = controllers;

Or just do that:

var app = req.app

inside the Middleware you are using for these routes. Like that:

router.use( (req,res,next) => {
    app = req.app;
    next();
});

For database separate out Data Access Service that will do all DB work with simple API and avoid shared state.

Separating routes.setup looks like overhead. I would prefer to place a configuration based routing instead. And configure routes in .json or with annotations.


Let's say that you have a folder named "contollers".

In your app.js you can put this code:

console.log("Loading controllers....");
var controllers = {};

var controllers_path = process.cwd() + '/controllers'

fs.readdirSync(controllers_path).forEach(function (file) {
    if (file.indexOf('.js') != -1) {
        controllers[file.split('.')[0]] = require(controllers_path + '/' + file)
    }
});

console.log("Controllers loaded..............[ok]");

... and ...

router.get('/ping', controllers.ping.pinging);

in your controllers forlder you will have the file "ping.js" with this code:

exports.pinging = function(req, res, next){
    console.log("ping ...");
}

And this is it....

참고URL : https://stackoverflow.com/questions/10090414/express-how-to-pass-app-instance-to-routes-from-a-different-file

반응형