In a GET request, how is data sent to the server?
Data is passed through the url, in the query string.
?heardItAlready=yes&nextThingPlease=ok
Is the query string encoded in any way? →
%26
- ampersand, %2F
- forward slash, %40
- at symbol&
be?%2525
Is there a way for our application to access the query string? →
Just check out the req.query property. Let's take a look. What's the simplest application we can write? It should just respond to / and log out query string data if any.. →
const express = require('express');
const app = express();
app.get('/', function(req, res) {
console.log(req.query);
});
app.listen(8080);
In order to access the data passed along in the data string, just look at req.query
.
Define a route, call render… and pass it some context: →
app.get('/', function(req, res) {
res.render('index', {'items':[1, 2, 3, 4, 5, 6]});
});
Create your surrounding html in views/layout.hbs
(don't forget body
with 3 curly braces): →
<!doctype html>
<html>
<body>
in the layout
{{{body}}}
</body>
</html>
And of course, a template. Here, we're iterating over the value items
passed in as the context
: →
{{#each items}}
- {{this}}
{{/each}}
Can we use query string params to filter the numbers we're seeing in the list? →
http://localhost:8080/?greaterThan=4
# show only numbers greater than 4 in the template!
// in your callback for / ...
const numbers = [1, 2, 3, 4, 5, 6];
const context = numbers;
if (req.query.greaterThan !== undefined) {
context = numbers.filter(function(num) {
return num > +req.query.greaterThan;
});
}
res.render('index', {'items':context});
Create a global stats variable (don't really do this, we'll find better data stores later) using data from the higher order functions slides. →
const stats = [
{"lastName":"Duncan", "team":"Spurs", "FGM":5, "FGA":10},
{"lastName":"Parker", "team":"Spurs", "FGM":7, "FGA":18},
{"lastName":"Ginobili", "team":"Spurs", "FGM":6, "FGA":11},
{"lastName":"James", "team":"Heat", "FGM":10, "FGA":21},
{"lastName":"Wade", "team":"Heat", "FGM":4, "FGA":12},
{"lastName":"Bosh", "team":"Heat", "FGM":6, "FGA":14}
];
In your route's callback function, create a similar filter, but for minimum field goals made: →
const minFgm = req.query.minFgm || 0;
const filteredPlayers = stats.filter(function(player) {
return player.fgm >= +minFgm;
});
res.render('index', {'players':filteredPlayers});
In the view. →
{{#each players}}
{{lastName}} - {{FGM}} field goals made
{{/each}}
Use this query string. →
?minFgm=3