How to creat an Express App

I. Express Project Structure

The best practice for organizing the files:

  • app.js: main file, houses the embedded server and application logic
  • /public: contains static files to be served by the embedded server
  • /routes: houses custom routing for the REST API servers (not needed for a web app)
  • /routes/users.js: endpoint/routes for resources such as users
  • /views: contains templates that can be processed by a template engine (not needed for REST APIs)
  • /package.json: project manifest
  • /www: boot up script folder

II.Creating an Express App

The main Express app (server) file is typically named app.js, server.js or index.js.

It has the following sections:

  • Imports
  • Instantiations
  • Configurations
  • Middleware
  • Routes
  • Error handlers
  • Server export
// Imports
const express = require("express");

// Express app
const app = express();

// Routes
app.get("/", (req, res) => {
  res.send("hello world");
});

// Listen for request
app.listen(3000);

The .send() method automatically sets the content type header.

III. Configuring Express

The Express server could be configured before it starts via the set method where the first argument is the name and the second is the value:

For example, we can set view to templates instead of the default value of views, and set template engine to jade.

const express = require("express");
const app = express();
app.set("port", process.env.PORT || 3000);
app.set("views", "templates"); // The directory the templates are stored in
app.set("view engine", "jade");