Routes

In notebook:
FrontEndMasters Building Web Apps with Node.js
Created at:
2015-10-08
Updated:
2015-10-09
Tags:
backend Node JS JavaScript
Video Course on Building Web Applications with Node.js
  • Respond to HTTP requests with a callback
  • Supports variable placement in routes (/user/id -> id as variable)
  • serve JSON - automatically sets headers, serialises yo JSON

Demo


​npm install express

app.js
  // app.js

var express = require("express");

var app = epxress(); // -> now I can start adding routes

app.listen(3000); // will automatically create the http server
then create the routes (insert around line #4 above)
  // supports http words (get, post, delete)

app.get("/", function(request, response){
    // request, response -> slightly decorated versions of the underlying nodejs response and request objects
    response.send("hello world from express!");
    // or you can automatically send json:
    response.send({
        foo: "bar"
    });
});


app.post("/doStuff", function(request, response){
    var param = request.param("foo"); // a POST parameter called "foo" we get from the request
    response.send({
        foo:param
    });
});
uses the chrome extension "POSTMAN", it's a graphical version of curl to use the rest api

NOTE: the above example will not work! we didn't tell express to parse the incoming the POST parameters -> need a middleware for that (before we arrive at the post url handler)

to mount a middleware: ​app.use()​ :

app.use(express.urlencoded())​ <- this will parse the url (add this to the above code)

Express does nothing out of the box, except for URL routing. Need to include middleware for all the rest