Pugs are unable to interpret arrays unless they are actively scanning through each element

Currently, I am engaged in a small Web development project for a University course. The project involves using Express with Pug as the view engine. My goal is to iterate through an array of weather stations, creating a unique route for each one. Each route should lead to a details page where the specific value from the array is displayed.

var i = 0;
while(stations[i]!= null){
    app.get('/'+stations[i]["name"], (req, res) => {
        res.render("DetailsTemplate", {Station: stations[i]})
    });
    console.log(`detailsPageRunning on ` + '/' + stations[i]["name"] + ' '+ i);
    i++;
}
block content
    div(class="details")

        div(class="station")
            div(class="station-element")
                h2 #{Station.name}
                p
            div(class="station-element")
                h2 Weather
                p #{Station.readings.at(0).weather}
            div(class="station-element")
                h2 Temperature
                p #{Station.readings.at(0).temp} Degrees
            div(class="station-element")
                h2 Wind
                p #{Station.readings.at(0).wind} bft.
            div(class="station-element")
                h2 Air Pressure
                p #{Station.readings.at(0).airpressure} bpa

Currently, the routes are created as intended and the page renders fine when using the same array value for each iteration, such as Station: stations[0]. However, the issue arises when trying to dynamically assign different values to each route using Station: stations[i]. What adjustments need to be made for this to work properly?

I have experimented with other arrays to see if the problem lies within the array itself, but encountered the same issue.

Answer №1

A demonstration of fulfilling the requirement using a route parameter is presented in the following code snippet. Another approach in a separate post involves utilizing an array of route paths.

server.js

const express = require('express');

const app = express();

// sample data
const stations = [
  { name: 's-one', readings: [{ wetter: 10, temp: 4, wind: 1, luftdruck: 5 }] },
  {
    name: 's-two',
    readings: [{ wetter: 12, temp: 14, wind: 13, luftdruck: 3 }],
  },
];

// utilizing a route parameter
app.get('/:stationname', (req, res, next) => {
  const routename = req.params.stationname;

  // finding station details based on the route parameter
  const station = stations.find((station) => station.name == routename);

  if (station) {
    // uncomment the below line when implementing render
    // res.render('DetailsTemplate', { Station: station });

    // sending data for testing purposes
    res.send(station);
  } else {
    // handle error for invalid requests
    next(new Error('Invalid station'));
  }
});

// Custom error handler
app.use((err, req, res, next) => {
  res.send(`Some Error : ${err.message} `);
});

app.listen(3000, () => console.log('Listening on port 3000'));

Starting the server:

node server.js

Valid route parameter test:

Request: curl http://localhost:3000/s-one
Response: {"name":"s-one","readings":[{"wetter":10,"temp":4,"wind":1,"luftdruck":5}]}%

Invalid route parameter test:

Request: curl http://localhost:3000/s-onex
Response: Some Error : Invalid station

Answer №2

Your code has established a foundation, and the code below further elaborates certain aspects of it. Take a look to see if it adds value. The code utilizes an array of route paths, with an alternative method that utilizes a route parameter, discussed separately.

server.js

const express = require('express');

const app = express();

// sample data
const stations = [
  { name: 's-one', readings: [{ wetter: 10, temp: 4, wind: 1, luftdruck: 5 }] },
  {
    name: 's-two',
    readings: [{ wetter: 12, temp: 14, wind: 13, luftdruck: 3 }],
  },
];

// array of route paths e.g. [/s-one, /s-two]
const routepaths = stations.map((i) => '/' + i.name);

// route paths in array
app.get(routepaths, (req, res, next) => {
  // finding station with respect to the given request
  const station = stations[routepaths.findIndex((i) => i == req.url)];

  if (station) {
    // call render here as this
    //res.render('DetailsTemplate', { Station: station });

    // this send is just for testing this sample code
    res.send(station);
  }
});

// This a catch-all middleware
// it is required in case an invalid request is made
app.use((req, res, next) => {
  res.status(404).send('Route not found');
});

// this is the custom error handler
app.use((err, req, res, next) => {
  res.status(500).send(`Some error : ${err.message}`);
});

app.listen(3000, () => console.log('Listening at port 3000'));

Starting the server

node server.js

Testing a valid request:

   Request:  curl http://localhost:3000/s-one
   Response: {"name":"s-one","readings":[{"wetter":10,"temp":4,"wind":1,"luftdruck":5}]}

Testing an invalid request:

   Request: curl http://localhost:3000/s-onex
   Response: Route not found

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

Steps for displaying a post's image when hovering over its link in WordPress

One section of my website displays the latest 6 posts, and here is the HTML code for it: <div class="latest-posts"> <div id="latest-posts-title"> <p>Latest Posts</p> </div> <div id="latest-posts-pictures" ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...

Creating a JSON tree using MongoDB data in a Node.js environment

There are numerous questions similar to mine, but unfortunately, none seem to fit my specific case. The closest one I found is Create a JSON tree in Node.Js from MongoDB, but it still doesn't quite work as expected. Perhaps this problem is just too ...

Unable to provide any input while utilizing npm prompts

After installing npm prompts, I encountered a strange issue. When trying to run the example code for npm prompts, I found that I couldn't enter any input at all. The underscore in the input field would blink for a few seconds, then the cursor would ju ...

revealing a particular field in jQuery during the validation process

Edit: Currently, I am utilizing the jquery validate plugin and have hidden all error messages initially. Upon checking a specific input field, my objective is to unhide the error message if it is invalid without causing error messages to appear in other f ...

Tips for extracting a specific attribute from an array of objects using both react and JavaScript while considering various conditions

I have a set of objects structured like this: const obj_arr = [ { id: '1', jobs: [ { completed: false, id: '11', run: { id: '6&apos ...

Properly handling the use of single and double quotation marks in variable declarations within a JavaScript file

I have a search box where users can enter their search text. For example, they can type book, 'book', or "book". The value entered in the search box is then assigned to a variable in the JavaScript file. var searchTerm = "${searchTerm}"; <br/ ...

Removing double double quotes for Javascript

My problem involves a string that represents longitude/latitude in the format of dd°mm'ss''W (note 2 single quotes after ss). To convert this string into its decimal representation, I am using the following code snippet: function dmsTodeg ...

Upon clicking, the Bootstrap dropdown button fails to open up

Recently while working on my Ruby on Rails project, I encountered an issue with implementing a dropdown button similar to the one on Bootstrap's site. Unfortunately, the button isn't functioning as expected and is throwing an error in the browser ...

I am facing difficulties in inserting information into the MongoDB database

I've encountered an issue while trying to add user data to my MongoDB database locally using post requests on Postman. Despite having an API set up in the userRoute file to handle these requests, no data is being added. Below is the code snippet: cons ...

Bootstrap: Display a single product on the Carousel Product Slider for the smallest view

I found an example I'm using at this link: I noticed that when I resize my BrowserWindow, the boxes start to shrink. However, when the width reaches about 990px, the single products are rearranged in a 4-block layout from the initial width. Is there ...

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

"Utilize axios in React to interpret and handle error bodies captured through parsing as a ReadableStream

When I sent a post request using axios in a React form to a PHP server, I encountered an issue where the error returned a ReadableStream in its body. However, when I used Postman, I did not have this problem and received readable errors instead. How can I ...

How to place an element in a specific location within the DOM using JavaScript

How can I position a created element in a specific place within the DOM using this code? Currently, it appends at the bottom of the page. var x = document.getElementById('options_10528_1'); var pos = document.getElementById('options-10528- ...

Utilizing JavaScript within my WordPress site

I'm experiencing some issues with my JavaScript code in WordPress. I have been trying to use the following code on my page, but it doesn't seem to work properly. Can someone please guide me on how to integrate this code within my WordPress page? ...

Adding a new value to an array of objects without altering the existing values in ReactJS and NextJS

I have a JSON file containing image names that I need to organize into a Key-Value Object. I am currently using regex to create keys by removing "-img[image No]". However, I am having trouble storing all the image names in the array without overwriting pre ...

Having trouble initializing and retrieving an array from the controller in AngularJS

I tried to set up and retrieve the array values from the controller. Check out the fiddle here. var app = angular.module('carApp', []); app.controller('carAppCtrlr', function ($scope) { $scope.vehicles = [{ type: ' ...

Ways to adjust the position of a DIV based on its index value

I'm currently working on a unique project that involves creating a triangular grid using HTML and CSS. The challenge I am facing is offsetting each triangle in the grid to the left by increasing amounts so they fit seamlessly next to one another. Righ ...

Error always appears when using addMethod in jQuery validator

$.validator.addMethod("validateEmail", function() { $.ajax({ type: "POST", url: "/user/check_email", data: { email: $( "#email" ).val() }, success: function(data) { console.log(dat ...

Identifying when a system window covers an iframe

After watching a fascinating YouTube video (https://www.youtube.com/watch?v=TzPq5_kCfow), I became intrigued by how certain features demonstrated in the video could be implemented using JavaScript. One specific question that arose for me was how one can d ...