One of the most powerful features of a server is the ability to modify behaviour based on the url.


Routes can be used to send JSON.

app.get('/api', function(req, res) {
    res.json({important: 'information'});
});

When defining your routes you can place a colon in front of the path to turn it into a variable.

app.get('/:whatever', function(req, res) {
    res.render('index', {
      what: req.params.whatever
    });
});

Express then access this variable as a property of req.params.

res.render accepts an object as a second argument—after the name of the template file—which then becomes accessible as a variable in the template.

<%= what %>

Significantly, you can also pass that variable to your client side JavaScript.

<script>
  var what = '<%= what %>';
</script>

Homework

Create a node app that grabs one or more variables from the URL. These will then affect some behaviour on your site. You may use APIs, jQuery, or any graphics library of your choosing (or not). Come prepared to class with a working file and we will upload it to a server before critiquing it.

Recommended

Read The Beginner Node Book by Manuel Kiessling (also uploaded to the drive).