访问/修改主文件中的数组来自路由文件/模块

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月12日 06:18:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定