Express에서 경로 핸들러를 여러 파일에 포함시키는 방법은 무엇입니까?
내 노드에서제이에스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
Express 4.x에서는 라우터 개체의 인스턴스를 가져오고 더 많은 경로가 포함된 다른 파일을 가져올 수 있습니다.이 작업을 반복적으로 수행하여 경로가 다른 경로를 가져오므로 유지 관리하기 쉬운 URL 경로를 만들 수 있습니다.
" ▁file▁for▁my경"에 대한 별도의 경로 파일이 /tests가 이미 "" "" " " " " "에 대한 새 ./tests/automated나는 이것들을 부수고 싶을지도 모릅니다./automated▁my▁to▁▁into를 로 라우팅합니다./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 '/tests'
.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;
@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);
});
}
그런 다음 경로 디렉토리에 경로 파일을 다음과 같이 배치합니다.
경로/테스트1.js
module.exports = function(app){
app.get('/test1/', function(req, res){
//...
});
//other routes..
}
필요한 만큼 반복하고 마침내 app.js 배치
require('./routes')(app);
typescript 및 ES6와 함께 express-4.x를 사용하는 경우 이 템플릿을 사용하는 것이 가장 좋습니다.
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");
});
사용하는 것보다 훨씬 깨끗함var그리고.module.exports.
재귀 라우팅.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' });
});
}
그리고 이전 답변인 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);
});
}
는 이 을 이답을업합니다고려하로 하려고 합니다."express": "^4.16.3"이 답변은 Short Round 1911의 답변과 유사합니다.
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/src/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/syswa/siswa_route입니다.js:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({item: 'Siswa page...'});
});
module.exports = app;
경로를 더 잘 구성하기 위해 별도의 .js 파일을 원한다면, 단지 변수를 만들 수 있습니다.app.js파일 시스템에서 해당 위치를 가리키는 파일:
var wf = require(./routes/wf);
그리고나서,
app.get('/wf', wf.foo );
어디에.foo당신의 안에 선언된 어떤 기능이 있습니까?wf.js파일. 예.
// wf.js file
exports.foo = function(req,res){
console.log(` request object is ${req}, response object is ${res} `);
}
다음과 같은 답변을 모두 수정합니다.
var routes = fs.readdirSync('routes')
.filter(function(v){
return (/.js$/).test(v);
});
배열의 각 파일을 테스트하여 필터링하려면 regex를 사용하십시오.재귀적이지 않지만 .js로 끝나지 않는 폴더를 필터링합니다.
이것이 오래된 질문이라는 것을 알지만, 저는 저 자신과 비슷한 것을 알아내려고 노력하고 있었고, 여기가 제가 처한 것과 같은 문제를 다른 누군가가 가지고 있는 경우에 대비하여 비슷한 문제에 대한 제 해결책을 찾고 싶었습니다.여기 보이는 많은 파일 시스템 작업(즉, readdirSync 작업 없음)을 수행하는 위탁이라는 멋진 노드 모듈이 있습니다.예:
저는 구축하려는 안정적인 API 애플리케이션이 있는데 '/api/*'로 이동하는 모든 요청을 인증받고 싶고 api로 이동하는 모든 경로를 자신의 디렉토리('api'라고 부르자)에 저장하고 싶습니다.앱의 주요 부분:
app.use('/api', [authenticationMiddlewareFunction], require('./routes/api'));
루트 디렉터리 안에 "api"라는 디렉터리와 api.js라는 파일이 있습니다.api.js에서 저는 다음과 같은 기능을 가지고 있습니다.
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;
모든 것이 예상대로 작동했습니다.이것이 누군가에게 도움이 되기를 바랍니다.
index.js
const express = require("express");
const app = express();
const http = require('http');
const server = http.createServer(app).listen(3000);
const router = (global.router = (express.Router()));
app.use('/books', require('./routes/books'))
app.use('/users', require('./routes/users'))
app.use(router);
routes/users.js
const router = global.router
router.get('/', (req, res) => {
res.jsonp({name: 'John Smith'})
}
module.exports = router
노선/도서
const router = global.router
router.get('/', (req, res) => {
res.jsonp({name: 'Dreams from My Father by Barack Obama'})
}
module.exports = router
서버가 로컬(http://localhost:3000)을 실행 중인 경우
// Users
curl --request GET 'localhost:3000/users' => {name: 'John Smith'}
// Books
curl --request GET 'localhost:3000/books' => {name: 'Dreams from My Father by Barack Obama'}
나는 이것을 하기 위해 작은 플러그인을 썼습니다! 같은 코드를 반복해서 쓰는 것에 싫증이 났습니다.
https://www.npmjs.com/package/js-file-req
도움이 되길 바랍니다.
모든 경로 함수를 다른 파일(파일)에 저장하고 주 서버 파일에 연결할 수 있습니다.메인 익스프레스 파일에 모듈을 서버에 연결하는 기능을 추가합니다.
function link_routes(app, route_collection){
route_collection['get'].forEach(route => app.get(route.path, route.func));
route_collection['post'].forEach(route => app.post(route.path, route.func));
route_collection['delete'].forEach(route => app.delete(route.path, route.func));
route_collection['put'].forEach(route => app.put(route.path, route.func));
}
각 경로 모델에 대해 해당 함수를 호출합니다.
link_routes(app, require('./login.js'))
모듈 파일(예: login.js 파일)에서 평소와 같이 기능을 정의합니다.
const login_screen = (req, res) => {
res.sendFile(`${__dirname}/pages/login.html`);
};
const forgot_password = (req, res) => {
console.log('we will reset the password here')
}
요청 메서드를 키로 사용하여 내보내고 값은 각각 경로 및 함수 키가 있는 개체 배열입니다.
module.exports = {
get: [{path:'/',func:login_screen}, {...} ],
post: [{path:'/login:forgotPassword', func:forgot_password}]
};
언급URL : https://stackoverflow.com/questions/6059246/how-to-include-route-handlers-in-multiple-files-in-express
'programing' 카테고리의 다른 글
| Xcode를 완전히 제거하고 모든 설정을 지우는 방법 (0) | 2023.05.11 |
|---|---|
| 마이크로소프트는 어디에 있습니까?ID 모델 dll (0) | 2023.05.11 |
| AltGr 키가 작동하지 않습니다. 대신 Ctrl+AltGr을 사용해야 합니다. (0) | 2023.05.11 |
| 이클립스:저장 시 코드를 포맷할 수 있습니까? (0) | 2023.05.11 |
| 하위 모듈이 아닌 경로에 대한 하위 모듈 매핑을 .git 모듈에서 찾을 수 없습니다. (0) | 2023.05.06 |