Express

A web framework for Node.js

Preparation

Create a package.json file and add express as a dependency at the CLI

npm init
npm install express --save

Initialize Express

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

Setup View Engine

The view engine setting determines the file extension

app.set("view engine", "ejs");

Rendering HTML to the client

Syntax

res.render(view [, locals] [, callback])

Renders a view and sends the rendered HTML string to the client (Ref: 232)

  • view, a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the views setting.
  • locals, an object whose:

    key: name reference to view file properties: local variables for the view.

res.render("home");

res.render("campgrounds", {campgrounds:campgrounds});
  • res.send() only output plain text

Routing & Sending Response

Syntax: Routing

app.get(path, callback [, callback ...]) Routes HTTP GET requests to the specified path with the specified callback functions.

Syntax: Sending Response

res.send([body]) Sends the HTTP response.

Staic Routing

app.get("/", function(req, res){
  res.send("Hi there!");
});

app.get("/bye", function(req, res){
  res.send("Goodbye!");
});

Routing with Parameters

See <a href="../../RESTful Routes/tbl_restful_routes.html" target = "_blank">RESTful routing</a>

app.get("/r/:subRedditName", function(req, res){
  var subReddit = req.params.subRedditName;
  res.send("Welcome to the " + subReddit.toUpperCase() + " Sub Reddit!!!");
});

Catch-All Route

Access a route that isn't defined above

app.get("*", function(req, res){
  res.send("You are a star!!");
});

Add Listener for requests

app.listen(3000, function(){
  console.log("Server has started!!")
});

Directory Layout

Directory Contains
model Database Schema files
public CSS files
views EJS Templates
views/partials header, footer, navbar EJS templates

Express File Layout