I'm getting a referenceError which I've been unable to figure out.
Any time I make a change to some code and upload it to the server, I refresh the page in the browser to see the changes - however 90% of the time I get a 502 Bad Gateway error on the first load of the index page - if I hit refresh, it loads fine without any errors.
The error in console is:
You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection:
ReferenceError: sugar is not defined
at /var/www/nodeapp/routes/index.js:80:17
at processTicksAndRejections (internal/process/task_queues.js:97:5)
- I've indicated the error is for 'sugar' but it could also be any of the other records (syrup, water, etc) - it seems random as to which one errors.
This is my code:
router.get('/', function(req, res, next) {
var waterSearch = '?Network=water&_sort=Votes'
var sugarSearch = '?Network=sugar&_sort=Votes'
var syrupSearch = '?Network=syrup&_sort=Votes'
var jellySearch = '?Network=jelly&_sort=Votes'
var promotedSearch = '?Promoted=true&_sort=Votes'
getRecords(waterSearch)
.then( data => {
return water = data
})
getRecords(sugarSearch)
.then( data => {
return sugar = data
})
getRecords(syrupSearch)
.then ( data => {
return syrup = data
})
getRecords(jellySearch)
.then ( data => {
return jelly = data
})
getRecords(promotedSearch)
.then ( data => {
return promo = data
})
.then( () => {
res.render('index', {
title: 'index',
addClass: 'homePage',
waterData: water,
sugarData: sugar,
syrupData: syrup,
jellyData: jelly,
promoData: promo
})
})
.catch(e => { console.log(e) })
});
The function it calls is:
function getRecords(searchString) {
return new Promise((resolve, reject) => {
var url = projectAPI + searchString
fetch(url)
.then(res => res.json())
.then(json => { resolve (json) })
.catch(e => { console.log(e) })
})
}
The data is being fetched from a strapi postgres cms on the same server.
As I mentioned, the error only occurs the very first time the index page is loaded from a browser after the app starts. After the browser page is refreshed everything works as it should.
Incidentally, if I have two browsers open - chrome and firefox, both browsers give the same error on the first load of the page - each browser has to be refreshed independently to get the index page to load properly.
If anyone could shed any light on what I'm missing, it would be most appreciated. Thanks in advance.