This is my unique code snippet from my router, where I am utilizing a Node Express server with Pug.
var express = require('express');
var router = express.Router();
var https = require('https');
/* GET home page. */
router.get('/', function(req, res, next) {
var url = 'https://data.police.uk/api/forces';
var data = [];
https.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var response = JSON.parse(body)
for (var i = 0; i< response.length; i++)
for (var id in response[i]) {
data[i] = response[i]
}
console.log(data[0].id);
});
}).on('error', function(e){
console.log("Error: ", e);
})
res.render('map', {
title: 'data[0].id'
});
});
module.exports = router;
In addition to the backend logic above, this is the corresponding Pug file that will be rendered.
p Welcome to #{title}
The console.log within 'res.on()' successfully displays the expected JSON package. However, when attempting to reference this array in res.render(), for example using title: 'data[0].name', it results in an undefined error.