Having trouble retrieving element from Pug data array

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.

Answer №1

Make sure to move the res.render function to the appropriate location where the data variable is filled with information:

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(response){
        var body = '';

        response.on('data', function(chunk){
            body += chunk;
        });

        response.on('end', function(){
            var responseData = JSON.parse(body)
            for (var i = 0; i< responseData.length; i++)
                for (var id in responseData[i]) {
                    data[i] = responseData[i]
                }
            console.log(data[0].id);
            res.render('map', {
                title: 'data[0].id'
            });
        });

    }).on('error', function(e){
        console.log("Error: ", e);
    })

});

module.exports = router;

Remember, asynchronous code requires careful placement of functions to ensure variables are populated correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on updating data dynamically in Vue.js

I am facing an issue with Vue JS in my frontend development. Here is the data for my component - data: () => ({ email: "", showError : false }), Below is the corresponding HTML code - <div v-show='showError' c ...

Utilizing HTML values within CSS3 content

I'm looking to integrate year numbers into circular shapes along a vertical timeline. My initial concept involves using CSS content and possibly leveraging JavaScript to extract data properties from the HTML, such as year="1958", and inserting it into ...

How can we integrate Cordova plugins into Vue-Cordova framework?

Looking to integrate Vue-Cordova with Cordova-plugin-file-opener2 to open PDF files within iOS/Android applications. In the Vue-Cordova setup, plugins related to the device are defined on the data property of the App vue instance: data: function () { ...

JavaScript call to enlarge text upon click

I'm struggling to figure out why my font enlargement function isn't working as expected. Below is the code for my font enlargement function: <script type="text/javascript> function growText() { var text = document.getElementBy ...

Using the code `$("img").one('load'` can trigger only a single load event without repetition

I have implemented the following function: function CheckImage(url, index) { $("<img/>").one('load', function () { $("div.photos").append(this); }).attr('src', url).attr('data-photo', '0' + ind ...

Express Test with Jest

My current project involves a controller that handles a simple car buying/selling API. The function in question looks like this: async processCarSale(@Res() res: any) { if(carSaleService.sale()) { return res.status(201).send(<some-body>); ...

What is the best method for accessing data values from HTML within a JavaScript function?

Greetings, I am relatively new to using jquery and ajax. Here is a snippet of my code: .html <li class="list-group-item"> <h2>Vocabulary</h2> <h4> <span class="label label-success">Like Name</span& ...

Express.js - Is there a way to serve distinct static directories for production and development environments?

My goal is to serve the ../client directory while in development, which contains the current files being edited. However, during production, I need to serve a folder called ../client/dist. How can I achieve this? I attempted to use a simple if condition, ...

Tips on effectively organizing information retrieved from an XML file?

I would like to organize the data in ascending order based on the DATE after making this ajax call function parseXML(xml){ var weatherArray = []; var weatherElement = xml.getElementsByTagName("forecast")[0]; weatherArray.queryTime = weatherEl ...

What is a reliable method for automatically refreshing a webpage despite encountering server errors?

I'm working on an HTML+JS web page that refreshes itself automatically every few seconds using http-equiv="refresh". The problem is, sometimes the server returns a 502 "bad gateway" error, preventing the HTML code from loading and causing th ...

When the focus() method is used to programmatically set the cursor in a JQuery input element, the blinking cursor does

I have a situation where I have two sibling divs. On the left side, I am loading a PDF document, while on the right side, I have input fields controlled by jQuery. My challenge arises when I try to select and delete the value from the input using the mous ...

What is the best way to establish a JavaScript function at the global level?

I need to make my function accessible globally in JavaScript. How can I accomplish this? Below is the function that I have: $(function () { function formatCurrency(input) { return input.toString().replace(/(\d)(?=(\d{3})+(?!\d) ...

Error: Custom Service is behaving unpredictably

My latest project involves creating a customized service. While the service function is returning data as expected, I encounter an issue when calling it in the controller - it returns 'undefined'. Service: var toDoListServices = angular.module( ...

Is it possible to use JQuery to swap out a blank div with the outcome of a load event?

I have a placeholder div nested inside another div. My goal is to swap out the placeholder div with data retrieved from a .load() call when the parent div is clicked on using its onclick function... Here's an example: function switchContent(projec ...

Unable to apply ready function in jquery .load

When the document is ready, the following code is executed: jQuery(document).ready(function(){ jQuery('#button').click(function() { jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt"); ...

Create a user-friendly responsive tooltip in Javascript/jQuery with a convenient close

Looking to implement a tooltip feature that appears when a text box is focused on my responsive website, and disappears when it loses focus. Can anyone recommend the best JavaScript/jQuery library for this specific purpose? Here are my requirements: T ...

Server initialization error in Node.js

I'm having trouble understanding the issue at hand: a) some users are able to start their server even with the missing module, so what is the error exactly? b) How can I go about fixing this? What I've attempted so far: rm -rf node_modules npm ...

Utilizing a JavaScript variable within an HTML style attribute value

I have added some divs to a webpage. I am looking to adjust the width of these divs based on the browser or other settings. While I can manually set the width to 200px using inline styles, I need the flexibility to change it to 220px, 230px, or 240px depen ...

Ways to apply CSS in jQuery using various combinators

I'm facing an issue with changing CSS using jQuery. The specific CSS line I want to modify is: .switch-vertical input ~ input:checked ~ .toggle-outside .toggle-inside { top: 40px; } My attempt at changing it looked like this: $('.switch-vertic ...

Strategies for handling uncaught promise rejections within a Promise catch block

I'm facing a challenge with handling errors in Promise functions that use reject. I want to catch these errors in the catch block of the Promise.all() call, but it results in an "Unhandled promise rejection" error. function errorFunc() { return ne ...