Routing - abbernie/web-dev-sp17 GitHub Wiki

In Express, we can set up the URLs our application will use. This is called routing. Set the name of the URL, or route, and then define a function to run when that URL is visited.

// url is http://yourdomain/one
app.get('/one',function(request,response){
    response.send('One');
});

// url is http://yourdomain/two
app.get('/two',function(request,response){
    var sum = 1 + 1;
    response.send('One plus one is ' + sum);
});

The content we output is dynamic, as you can see in the route for "/two", where first we do a calculation, and then use the result in the output text.

Sometimes we may need to send a static file, for example, an HTML file that we don't expect to change.

// url is http://yourdomain/about
app.get('/about',function(request,response){
    response.sendFile('./about.html');
}

Each function called in .get() takes a request and response parameter, often abbreviated to req and res, which contain information about the user's request and lets you respond to the request.

Route Parameters

The exciting part comes when the route handler can take in additional information and give a customized response based on that information. Define a variable in a route by using a colon (:) in front of the variable name. Then retrieve the value of the variable from the request object using request.params.VARIABLE_NAME.

// url is http://yourdomain/profile/jack or http://yourdomain/profile/jill, etc.
app.get('/profile/:username',function(req,res){
    res.send("All about " + request.params.username);
});

The example above will return "All about jack" when the URL is http://yourdomain/profile/jack and "All about jill" when the URL is http://yourdomain/profile/jill.