英文:
Accessing/Modifying array in main file from route file/module
问题
在主文件(index.js)中,我有一个数组,我想要在一个包含一个端点路由的单独文件中修改它(向其中添加元素):
主文件(index.js)中的代码:
let arr = [];
app.use('/create', require("./routes/.../module.js"));
module.js 中的代码:
const express = require("express");
const router = express.Router();
router.post("/", async (req, res) => {
// 这里是我想要运行的代码,用来向主文件中的 arr 数组添加元素
});
module.exports = router;
英文:
(I am using express.js)
I have an array in my main file that I would like to modify (add elements to) from a separate file that contains a router for one of my endpoints:
Code in my main file (index.js):
let arr = [];
app.use('/create', require("./routes/.../module.js"));
Code in module.js:
const express = require("express");
const router = express.Router();
router.post("/", async (req, res) => {
// here is where I would like to run code that would add something to the arr array in my main file
});
module.exports = router;
答案1
得分: 0
如果您正在使用express.js,一种将值传递给路由处理程序的方法是使用app.locals。通过这样做,您可以在module.js
中访问arr
。以下是一个简单的示例:
// index.js
app.locals.myArr = arr;
// module.js
module.exports.myhandler = function(req, res)
{
let myArr = req.app.locals.myArr;
//...
};
有关app.locals的更多信息,请访问:https://expressjs.com/en/api.html
希望这个答案有所帮助。
英文:
If you are using express.js, one way of passing a value to route handlers and is to use app.locals. By doing this, you can access arr
in module.js
. Here would be a simple example of that:
// index.js
app.locals.myArr = arr;
// module.js
module.exports.myhandler = function(req, res)
{
let myArr = req.app.locals.myArr;
//...
};
For more information on app.locals: https://expressjs.com/en/api.html
Hope this answer helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论