启动我的应用程序时,将创建一个对象,该对象将在整个应用程序中的多个文件中使用。在我的app.js文件中,我需要几个包含我的路线的文件。这些路由需要访问在app.js中创建的对象,因此我试图将其传递给每个文件。下面是其中一个文件的示例。
test.js
const express = require('express');
const router = express.Router();
router.use('/api', router);
router.post('/testRoute', (req, res, next) => {
if(globalVariable.abc) { //globalVariable is the variable created in app.js
//do some logic
}
res.json({
message: "Test Route Success"
})
});
module.exports = router;
app.js
const assessmentRoutes = require('./routes/test');
app.use(assessmentRoutes);
我尝试传递变量的一种方法是将路由包装在test.js中的函数中,该函数采用这样的变量。
module.exports = function(globalVariable) {
router.post('/testRoute', (req, res, next) => {
if(globalVariable.abc) { //globalVariable is the variable created in app.js
//do some logic
}
res.json({
message: "Test Route Success"
})
});
}
然后在app.js中将要求更改为:
const assessmentRoutes = require('./routes/assessments')(globalVariable);
当我这样做时,在启动应用程序(例如app.use())时遇到错误,需要一个中间件功能。
如何将对象传递到路线中?
答案 0 :(得分:1)
一种方法which I don't recommend使用global
对象:
app.js
const assessmentRoutes = require('./routes/test');
global.globalVariable = { abc: ... };
app.use(assessmentRoutes);
test.js
const express = require('express');
const router = express.Router();
router.post('/testRoute', (req, res, next) => {
if (globalVariable.abc) { ... }
res.json({
message: 'Test Route Success',
});
});
module.exports = router;
另一种方法是导出一个函数,您可以像以前那样将其作为参数传入。问题是您没有从该函数返回路由器,以后需要在app.js
中使用:
app.js
const assessmentRoutes = require('./routes/test');
app.use(assessmentRoutes({ abc: ... }));
test.js
const express = require('express');
const router = express.Router();
module.exports = function(globalVariable) {
router.post('/testRoute', (req, res, next) => {
if (globalVariable.abc) { ... }
res.json({
message: 'Test Route Success',
});
});
// This is what you were missing in your code!
return router;
};
类似的选择是导出router
对象以及setter函数以在globalVariable
内部初始化test.js
:
app.js
const { assessmentRoutes, initAssessmentRoutes } = require('./routes/test');
initAssessmentRoutes({ abc: ... });
app.use(assessmentRoutes);
test.js
const express = require('express');
const router = express.Router();
let globalVariable = { abc: null };
function initAssessmentRoutes(options) {
globalVariable = options;
}
router.post('/testRoute', (req, res, next) => {
if (globalVariable.abc) { ... }
res.json({
message: 'Test Route Success',
});
});
module.exports = {
assessmentRoutes: router,
initAssessmentRoutes,
};
答案 1 :(得分:0)
APP.JS
app.locals.globalVariable= {type:"Fiat", model:"500", color:"white"};
TEST.JS
if (req.app.locals.globalVariable.type =="Fiat" ) {
.....
}
答案 2 :(得分:0)
在您的test.js中摆脱:
router.use('/api', router);
在您的app.js中,更改以下行:
app.use('/', assessmentRoutes);
这应该可行。