Javascript 从server.js app.get调用获取对象到js文件中进行API调用
我有一个server.js,其中有我所有的app.get调用,其中一个我正试图将一个数组导出到另一个javascript文件中,以用于不同的API调用。这是我拥有的端点:Javascript 从server.js app.get调用获取对象到js文件中进行API调用,javascript,node.js,Javascript,Node.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 currentl
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);
这提供了一个错误说明
“pscript.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);
const exportedArray = require('../server.js');
module.exports.foo = function(){
const myArr = exportedArray();
console.log('this is in the pscript file', myArr);
}
请注意,它将打印一个空数组,因为“require”在运行时运行,所以myArr为空。您应该在另一个函数中使用它:
const exportedArray = require('../server.js');
const myArr = exportedArray();
console.log('this is in the pscript file', 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将正确打印
- 注**