Express에서 여러 파일에 라우트 핸들러를 포함시키는 방법은 무엇입니까?
내 NodeJS express
응용 프로그램 app.js
에는 몇 가지 공통 경로가 있습니다. 그런 다음 wf.js
파일에서 몇 가지 경로를 더 정의하고 싶습니다.
파일에 app.js
정의 된 다른 경로 처리기를 어떻게 인식 할 수 wf.js
있습니까?
간단한 요구 가 작동하지 않는 것 같습니다.
당신이하려는 경우 별도의 파일에 경로를 넣어 , 예를 들어 routes.js
, 당신은 만들 수 있습니다 routes.js
이 방법으로 파일 :
module.exports = function(app){
app.get('/login', function(req, res){
res.render('login', {
title: 'Express Login'
});
});
//other routes..
}
그런 다음 이 방법으로 객체 를 app.js
전달하지 않아도됩니다 .app
require('./routes')(app);
이 예제도 살펴보십시오
https://github.com/visionmedia/express/tree/master/examples/route-separation
@ShadowCloud의 예를 바탕으로 하위 디렉토리에 모든 경로를 동적으로 포함시킬 수있었습니다.
routes / index.js
var fs = require('fs');
module.exports = function(app){
fs.readdirSync(__dirname).forEach(function(file) {
if (file == "index.js") return;
var name = file.substr(0, file.indexOf('.'));
require('./' + name)(app);
});
}
그런 다음 다음과 같이 경로 파일을 경로 디렉토리에 배치하십시오.
routes / test1.js
module.exports = function(app){
app.get('/test1/', function(req, res){
//...
});
//other routes..
}
필요에 따라 여러 번 반복 한 다음 마침내 app.js 배치
require('./routes')(app);
이것은 오래된 질문이지만 비슷한 문제에 대한 해결책을 찾기 위해 여기에서 우연히 발견되었습니다. 여기에 몇 가지 솔루션을 시도한 후에 다른 방향으로 가고 결국 여기에있는 다른 사람을 위해 솔루션을 추가 할 것이라고 생각했습니다.
express 4.x에서는 라우터 객체의 인스턴스를 가져와 더 많은 경로가 포함 된 다른 파일을 가져올 수 있습니다. 이 과정을 재귀 적으로 수행하여 경로가 다른 경로를 가져 와서 유지하기 쉬운 URL 경로를 만들 수 있습니다. 예를 들어, '/ tests'엔드 포인트에 대한 별도의 라우트 파일이 이미 있고 '/ tests / automated'에 대한 새로운 라우트 세트를 추가하려는 경우이 '/ automated'라우트를 다른 파일로 분리 할 수 있습니다. 내 '/ test'파일을 작고 관리하기 쉽도록 유지하십시오. 또한 URL 경로별로 논리적으로 경로를 그룹화 할 수있어 매우 편리합니다.
./app.js의 내용 :
var express = require('express'),
app = express();
var testRoutes = require('./routes/tests');
// Import my test routes into the path '/test'
app.use('/tests', testRoutes);
./routes/tests.js의 내용
var express = require('express'),
router = express.Router();
var automatedRoutes = require('./testRoutes/automated');
router
// Add a binding to handle '/test'
.get('/', function(){
// render the /tests view
})
// Import my automated routes into the path '/tests/automated'
// This works because we're already within the '/tests' route so we're simply appending more routes to the '/tests' endpoint
.use('/automated', automatedRoutes);
module.exports = router;
./routes/testRoutes/automated.js의 내용 :
var express = require('express'),
router = express.Router();
router
// Add a binding for '/tests/automated/'
.get('/', function(){
// render the /tests/automated view
})
module.exports = router;
그리고 이전 답변에서 더 많은 것을 빌드하십시오.이 버전의 routes / index.js는 .js로 끝나지 않는 파일 (및 자체)을 무시합니다.
var fs = require('fs');
module.exports = function(app) {
fs.readdirSync(__dirname).forEach(function(file) {
if (file === "index.js" || file.substr(file.lastIndexOf('.') + 1) !== 'js')
return;
var name = file.substr(0, file.indexOf('.'));
require('./' + name)(app);
});
}
폴더 .js
안에 있는 모든 파일 의 전체 재귀 라우팅 ./routes
app.js
// Initialize ALL routes including subfolders
var fs = require('fs');
var path = require('path');
function recursiveRoutes(folderName) {
fs.readdirSync(folderName).forEach(function(file) {
var fullName = path.join(folderName, file);
var stat = fs.lstatSync(fullName);
if (stat.isDirectory()) {
recursiveRoutes(fullName);
} else if (file.toLowerCase().indexOf('.js')) {
require('./' + fullName)(app);
console.log("require('" + fullName + "')");
}
});
}
recursiveRoutes('routes'); // Initialize it
에 /routes
당신을 넣어 whatevername.js
와 같은 당신의 경로를 초기화 :
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('index', { title: 'index' });
});
app.get('/contactus', function(req, res) {
res.render('contactus', { title: 'contactus' });
});
}
이 답변을 "express": "^ 4.16.3"으로 업데이트하려고합니다. 이 답변은 ShortRound1911과 유사합니다.
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const db = require('./src/config/db');
const routes = require('./src/routes');
const port = 3001;
const app = new express();
//...use body-parser
app.use(bodyParser.urlencoded({ extended: true }));
//...fire connection
mongoose.connect(db.url, (err, database) => {
if (err) return console.log(err);
//...fire the routes
app.use('/', routes);
app.listen(port, () => {
console.log('we are live on ' + port);
});
});
/src/routes/index.js
const express = require('express');
const app = express();
const siswaRoute = require('./siswa_route');
app.get('/', (req, res) => {
res.json({item: 'Welcome ini separated page...'});
})
.use('/siswa', siswaRoute);
module.exports = app;
/src/routes/siswa_route.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({item: 'Siswa page...'});
});
module.exports = app;
이것이 누군가를 도울 수 있기를 바랍니다. 행복한 코딩!
이 모든 답변을 한 번 조정하십시오.
var routes = fs.readdirSync('routes')
.filter(function(v){
return (/.js$/).test(v);
});
배열의 각 파일을 테스트하여 정규식을 사용하여 필터링하십시오. 재귀는 아니지만 .js로 끝나지 않는 폴더를 필터링합니다.
I know this is an old question, but I was trying to figure out something like for myself and this is the place I ended up on, so I wanted to put my solution to a similar problem in case someone else has the same issues I'm having. There's a nice node module out there called consign that does a lot of the file system stuff that is seen here for you (ie - no readdirSync stuff). For example:
I have a restful API application I'm trying to build and I want to put all of the requests that go to '/api/*' to be authenticated and I want to store all of my routes that go in api into their own directory (let's just call it 'api'). In the main part of the app:
app.use('/api', [authenticationMiddlewareFunction], require('./routes/api'));
Inside of the routes directory, I have a directory called "api" and a file called api.js. In api.js, I simply have:
var express = require('express');
var router = express.Router();
var consign = require('consign');
// get all routes inside the api directory and attach them to the api router
// all of these routes should be behind authorization
consign({cwd: 'routes'})
.include('api')
.into(router);
module.exports = router;
Everything worked as expected. Hope this helps someone.
If you want a separate .js file to better organize your routes, just create a variable in the app.js
file pointing to its location in the filesystem:
var wf = require(./routes/wf);
then,
app.get('/wf', wf.foo );
where .foo
is some function declared in your wf.js
file. e.g
// wf.js file
exports.foo = function(req,res){
console.log(` request object is ${req}, response object is ${res} `);
}
If you're using express-4.x with TypeScript and ES6, this would be a best template to use;
src/api/login.ts
import express, { Router, Request, Response } from "express";
const router: Router = express.Router();
// POST /user/signin
router.post('/signin', async (req: Request, res: Response) => {
try {
res.send('OK');
} catch (e) {
res.status(500).send(e.toString());
}
});
export default router;
src/app.ts
import express, { Request, Response } from "express";
import compression from "compression"; // compresses requests
import expressValidator from "express-validator";
import bodyParser from "body-parser";
import login from './api/login';
const app = express();
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.get('/public/hc', (req: Request, res: Response) => {
res.send('OK');
});
app.use('/user', login);
app.listen(8080, () => {
console.log("Press CTRL-C to stop\n");
});
Much clear rather using var
and module.exports
.
This is possibly the most awesome stack overflow question/answer(s) ever. I love Sam's/Brad's solutions above. Thought I'd chime in with the async version that I implemented:
function loadRoutes(folder){
if (!folder){
folder = __dirname + '/routes/';
}
fs.readdir(folder, function(err, files){
var l = files.length;
for (var i = 0; i < l; i++){
var file = files[i];
fs.stat(file, function(err, stat){
if (stat && stat.isDirectory()){
loadRoutes(folder + '/' + file + '/');
} else {
var dot = file.lastIndexOf('.');
if (file.substr(dot + 1) === 'js'){
var name = file.substr(0, dot);
// I'm also passing argv here (from optimist)
// so that I can easily enable debugging for all
// routes.
require(folder + name)(app, argv);
}
}
});
}
});
}
My directory structure is a little different. I typically define routes in app.js (in the root directory of the project) by require
-ing './routes'
. Consequently, I'm skipping the check against index.js
because I want to include that one as well.
EDIT: You can also put this in a function and call it recursively (I edited the example to show this) if you want to nest your routes in folders of arbitrary depth.
I wrote a small plugin for doing this! got sick of writing the same code over and over.
https://www.npmjs.com/package/js-file-req
Hope it helps.
'Programming' 카테고리의 다른 글
Java 컴파일러 레벨이 설치된 Java 프로젝트 패싯 버전과 일치하지 않습니다. (0) | 2020.05.10 |
---|---|
다른 테이블의 값이있는 mysql 업데이트 열 (0) | 2020.05.10 |
두 개의 하위 문자열 사이에서 문자열 찾기 (0) | 2020.05.10 |
MacOS Xcode CoreSimulator 폴더가 매우 큽니다. (0) | 2020.05.10 |
플로팅 요소가 포함 된 컨테이너 요소의 높이가 왜 증가하지 않습니까? (0) | 2020.05.10 |