Express

  1. Overview
    1. Express is a popular npm package for building web servers
    2. Install
      $ npm install express
      
  2. Simple web server
    1. Web server listens on port 4000
      // server.js
      var express = require('express');
      var app = express();
      
      app.get('/', function(req, res) {
          res.status(200).send('Hello Express!');
      });
      
      app.listen(4000);
      console.log("Server is listening on port 4000");
      
    2. Run server.js and access URL in web browser
      http://localhost:4000/
      
    3. Parse post string
      1. Install body-parser
        npm install --save body-parser
        
      2. Use body-parser to parse URL encoded data
        var bodyParser = require('body-parser');
        app.use(bodyParser.urlencoded({
            extended: true
        }));
        
      3. Look for post data "name" and "color"
        // POST: name=Bob&color=red
        app.post('/', function(req, res) {	
            var results = req.body.name + ' and ' + req.body.color;
            console.log(results);    // Bob and red
        	res.status(200).send(results);
        });						
        
      4. Test with HTML form or Postman - REST Client for Chrome
    4. Parsing JSON
      1. Web services often receive data in JSON format
      2. Add additional body parser
        app.use(bodyParser.json());
        
      3. No changes to app.post method
      4. Make sure HTTP request uses Content-Type: application/json so the correct parser will execute
      5. Example HTTP post
        POST / HTTP/1.1
        Host: localhost:4000
        Content-Type: application/json
        Cache-Control: no-cache
        
        {"name":"Sue","color":"blue"}