将server.jsapp.get调用中的对象获取到API调用的js文件中



我有一个server.js,其中我有我所有的app.get调用,其中一个调用我正在尝试将数组导出到另一个javascript文件,以便在不同的API调用中使用。这是我的终点:

app.get('/getInventory', checkNotAuthenticated, (req,res)=>{
var email = {user: req.user.email}; // used to obtain the email of the user thats logged in currently
var currUser = email.user;
pool
.query(`SELECT itemname FROM inventory WHERE email = $1`, [currUser]) 
.then((results)=>{
console.log(results.rows);
var myArr = [];
results.rows.forEach((item)=>{
myArr.push(item.itemname);
});
console.log(myArr);
module.exports = {myArr};
res.render('search')
})
.catch((err) =>{
console.log(err)

})})

这就是我试图导入myArr的地方。当用户想要根据/getInventory端点的返回进行搜索时,我想要在一个调用api的js文件中使用这个myArr。

const {myArr} = require('../server.js');
console.log('this is in the pscript file', myArr);

这提供了一个错误,称

"js:3未捕获引用错误:未定义require;

我看了几个堆栈溢出的帖子,这就是我如何得到这个解决方案的原因。不知道如何管理这个路障。我使用的是express和nodeJS。如果有任何其他信息,你需要帮助这个问题。我会尽我所能。非常感谢。

在导出任何内容之前运行'require'。您需要将myArr保留在本地作用域中,并在运行时获取它。

let myArr = []
module.exports = ()=> myArr;
app.get('/getInventory', checkNotAuthenticated, (req,res)=>{
var email = {user: req.user.email}; // used to obtain the email of the user thats logged in currently
var currUser = email.user;
pool
.query(`SELECT itemname FROM inventory WHERE email = $1`, [currUser]) 
.then((results)=>{
console.log(results.rows);
myArr = [];
results.rows.forEach((item)=>{
myArr.push(item.itemname);
});
console.log(myArr);
res.render('search')
})
.catch((err) =>{
console.log(err)

})})

然后,每次需要数组时,只需调用它的函数:

const exportedArray = require('../server.js');
const myArr = exportedArray();
console.log('this is in the pscript file', myArr);

请注意,它将打印一个空数组,因为"require"在运行时运行,因此myArr为空。你应该在另一个功能中使用它:

const exportedArray = require('../server.js');
module.exports.foo = function(){
const myArr = exportedArray();
console.log('this is in the pscript file', myArr);
}

现在,如果在server.js运行后调用"foo"方法,myArr将正确打印。

  • 注意**

顺便说一句,这不是一个好的做法。如果你不止一次需要一些数据,它应该分离成一个新的模块,并在需要的地方被调用,

最新更新