我真的很难将变量传递给另一个路由器。然后将它们传递给.pug。当我尝试在3.js中使用它们时,我变得不确定。我知道我必须使用回调,并且要花数小时才能浏览多个资源,但无法解决。
1.js
// normal setup
app.use(require('../routes/2').router);
app.use(require('../routes/3').router);
// server listen
2.js
const router = require('express').Router();
var fetch = require('fetch-retry');
let restcountries = require('rest-countries-node');
restcountries = new restcountries;
let data_fsq = {};
let elements = {};
restcountries.getAll()
.then(data => {
router.get('/data', function (req, res) {
res.json(data);
});
elements = data; // use this variable in 2.js
for (let element in data) {
http = `www.url,com`;
fetch(http, {
retries: 1
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw new Error('err');
}
})
.then(body => {
data_fsq[data[element].id] = body.items;
router.get(`/api/data/${i}`, function (req, res) {
res.json(body);
});
})
.catch((error) => {
console.log('error loading the data for: '+data_fsq[element].name);
});
}
});
module.exports = {
router: router,
data_fsq: data_fsq, // undefined
elements: elements //undefined
}
3.js
var data_fsq = require('./load').data_fsq;
var elements = require('./load').elements;
const path = require('path');
const router = require('express').Router();
router.post('/element/data', function (req, res) {
index = req.body.index;
});
router.get('/main', function (req, res) {
res.render(path.join(__dirname, '../client/main'){
data_fsq: data_fsq[index], // undefined
elements: elements[index] // undefined
})
});
module.exports = router;