Nodejs 路由文件里如何访问到app.js引入的模块?
Nodejs 路由文件里如何访问到app.js引入的模块?
在学利用 express 开发网站
app.js
var xxx = require(‘xxx’); app.get(’/’,route);
我这个route里怎么获取到xxx呢?
4 回复
一般是在 route 里面再引入该文件一次。
我总觉得这样是不是不友好呢?
通过参数传过去的话 也觉得代码不好看.
在Express应用中,app.js
文件通常负责设置应用的基本配置、中间件以及路由。如果你想在路由文件中访问通过 app.js
引入的模块(如 xxx
),可以通过以下几种方法实现:
方法一:直接传递给路由
你可以将需要的模块直接传递给路由处理函数。
app.js 示例代码:
const express = require('express');
const app = express();
const xxx = require('./path/to/xxx');
// 假设你有一个名为 route.js 的路由文件
const route = require('./routes/route')(xxx);
app.use('/', route);
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
route.js 示例代码:
module.exports = function(xxx) {
return (req, res) => {
// 现在你可以在路由处理函数中使用 xxx
res.send(`Hello from route.js using ${xxx}`);
}
}
方法二:使用全局变量
虽然不推荐,但你可以将模块赋值给全局变量 global.xxx
。
app.js 示例代码:
const express = require('express');
const app = express();
global.xxx = require('./path/to/xxx');
const route = require('./routes/route');
app.use('/', route);
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
route.js 示例代码:
module.exports = (req, res) => {
// 现在你可以在路由处理函数中使用 global.xxx
res.send(`Hello from route.js using ${global.xxx}`);
}
方法三:使用依赖注入容器
对于更复杂的项目,可以考虑使用依赖注入容器来管理模块和其依赖关系。
以上是几种在路由文件中访问 app.js
引入模块的方法。直接传递是最常见和推荐的方式,因为它保持了代码的清晰和可维护性。