0

I am working on a small Web-development project, express with pug as the view-engine, for my University-course. I wish to iterate through an array of Weather-stations, creating a route for every one, with a details-page where the value of 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 Wetter
                p #{Station.readings.at(0).wetter}
            div(class="station-element")
                h2 Temperatur
                p #{Station.readings.at(0).temp} Grad
            div(class="station-element")
                h2 Wind
                p #{Station.readings.at(0).wind} bft.
            div(class="station-element")
                h2 Luftdruck
                p #{Station.readings.at(0).luftdruck} bpa

Now the routes are created just as i want them to, and the page is able to render fine, if i give it, through every iteration, the same array. For example Station: stations[0] works fine. It is just kinda useless if i cant have different values on every route. Why does Station: stations[i] not work? What would i have to change for it to work?

I have tried using other arrays, to see weather the problem was with the array, but those showed the same problem.

1
  • 2
    you dont need to create route for every station, check out the express route on how to create dynamic route. Something like this should work: app.get('/station/:stationID', (req, res) =>... Commented Jun 7 at 13:01

2 Answers 2

0

The code below shows addressing the requirement using a route parameter. The other post uses 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 }],
  },
];

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

  // finding the station details with respect to the route parameter
  const station = stations.find((station) => station.name == routename);

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

    // this send is just for testing purpose
    res.send(station);
  } else {
    // throw error for invalid requests
    next(new Error('Invalid station'));
  }
});

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

app.listen(3000, () => console.log('L@3000'));

Running the server:

node server.js

Testing a valid route parameter

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

Testing an invalid route parameter

Request: curl http://localhost:3000/s-onex
Response: Some Error : Invalid station
1
  • Hi, Your feedback if any would be highly appreciated. Commented Jun 14 at 2:46
0

Your code has set the basis, the code below code clarifies certain points in it. Please see if it is useful. The code employs an array of route paths. There is another method using a route parameter, posted 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('L@3000'));

Running 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.