Nodejs 将变量从路由器文件传递到另一个路由器文件
Nodejs pass variable from router file to another router file
我需要将名为 path
的变量从路由器文件 lessonsRouter.js
传递到另一个路由器文件 lessons.js
我的文件夹结构
routes
|
+--lessons.js
|
+--lessonsRouter.js
lessonsRouter.js
const router = require('express').Router();
const lessons = require('./lessons');
router.get('/*/([A-Z][a-z]+)/README.md', (req, res) => {
const path = req.url; // the variable that i need to pass to lessons.js router
// ignore next three lines
const pathSeparate = req.url.split('/');
const LessonTopic = pathSeparate[1].toLowerCase()
const LessonName = pathSeparate[2].match(/[A-Z][a-z]+/g).join('-').toLowerCase();
res.locals.path = path;
res.redirect(`/lessons/${LessonTopic}/${LessonName}`);
});
router.use('/:topic/:name', lessons);
module.exports = router;
lessons.js
const router = require('express').Router();
router.get('/', (req, res) => {
// i want to use variable path from lessonsRouter.js here
});
module.exports = router;
我认为你 dependency/import 方向错了。 lessons
应该从 lessonsRouter
导入。但是如果你真的想要这样,那么你可以导出一个函数,你可以将路径 一旦你拥有它 .
lessonsRouter.js
const lessons = require('./lessons');
router.get('/*/([A-Z][a-z]+)/README.md', (req, res) => {
const path = req.url; // the variable that i need to pass to lessons.js router
lessons(path);
...
});
lessons.js
module.exports = (path) => {
router.get('/', (req, res) => {
console.log(path);
});
};
我需要将名为 path
的变量从路由器文件 lessonsRouter.js
传递到另一个路由器文件 lessons.js
我的文件夹结构
routes
|
+--lessons.js
|
+--lessonsRouter.js
lessonsRouter.js
const router = require('express').Router();
const lessons = require('./lessons');
router.get('/*/([A-Z][a-z]+)/README.md', (req, res) => {
const path = req.url; // the variable that i need to pass to lessons.js router
// ignore next three lines
const pathSeparate = req.url.split('/');
const LessonTopic = pathSeparate[1].toLowerCase()
const LessonName = pathSeparate[2].match(/[A-Z][a-z]+/g).join('-').toLowerCase();
res.locals.path = path;
res.redirect(`/lessons/${LessonTopic}/${LessonName}`);
});
router.use('/:topic/:name', lessons);
module.exports = router;
lessons.js
const router = require('express').Router();
router.get('/', (req, res) => {
// i want to use variable path from lessonsRouter.js here
});
module.exports = router;
我认为你 dependency/import 方向错了。 lessons
应该从 lessonsRouter
导入。但是如果你真的想要这样,那么你可以导出一个函数,你可以将路径 一旦你拥有它 .
lessonsRouter.js
const lessons = require('./lessons');
router.get('/*/([A-Z][a-z]+)/README.md', (req, res) => {
const path = req.url; // the variable that i need to pass to lessons.js router
lessons(path);
...
});
lessons.js
module.exports = (path) => {
router.get('/', (req, res) => {
console.log(path);
});
};