Codeschool Express.js Notes

Building blocks of Express.js on CodeSchool,  notes below… If you’re interested for more in depth tutorial about Node.js and Express, make sure you check out the 2nd tutorial (free, OFC) in a MEAN series I made for HackHands named Delving into Node.js and Express web framework.

Level 1

Install Express with npm:

npm install express

Simples web server which responds with Howdy!

var express = require('express');
var app = express();

app.get('/', function(req, res){
    res.json("Howdy!");
});

app.listen(1337); //tcp port btw

Test with curl (-i switch prints the headers):

curl -i http://localhost:1337

Redirecting the requests:

res.redirect(301, '/newLink');

Level 2

Static middleware to serve files from folder public.

app.use(express.static('public'));
app.use(function(req, resp, next){
    ...some work, when done call Ghost buster, erm, no
    next();
});

Level 3

app.get('/blocks', function(request, response) {
    //request.query.limit
    //if the request was like /api?limit=10
});
app.get('/blocks/:name', function(request, response) {
    //request.params.name
});

Level 4

//npm install body-parser

var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false });
//false forces the use of the native querystring Node library

app.post('/api', parseUrlencoded, function(request, response) {
var blocks = { ... };
var newBlock = request.body;
});

Level 5

app.route('/cities')
.get(function (request, response) {
})
.post(parseUrlencoded, function (request, response) {
});

Instead of

app.get('/apiEndpoint', function (request, response) {
});
app.post('/apiEndpoint', parseUrlencoded, function (request, response) {
});

Using the router to put in different file:

var router = express.Router();

router.route('/', router)
  .get(function (request, response) {
  })
  .post(parseUrlencoded, function (request, response) {
  });

router.route('/:name', router)
  .get(function (request, response) {
  })
  .delete(function (request, response) {
  });

app.use('/cities', router);
Written by Nikola Brežnjak