The main Express app (server) file is typically named index.js, app.js, or server.js.
A typical structure of an Express server file contains the following sections:
In this example, we create a simple Hello world app.
Basic server syntax
// Imports Express
const express = require("express");
// Initialize Express app
const app = express();
// Create a variable for the PORT number
const PORT = process.env.PORT || 3000;
// Routes
app.get("/", (req, res) => {
res.send("Hello World");
});
// Listen for request
app.listen(3000);
To start the server, run:
node index.js
This will start the server on port 3000. When we access http://localhost:3000, we will see the message Hello World.
Firstly, we use the require() function to import the express module.
const express = require("express");
Next line of code, we define an app instance to handle the request and response from the server to the client.
const app = express();
Next, we declare where the user can access it and how the server will respond.
app.get() tells the server what to do when a get request is called. It has a callback function that receives 2 objects, req and res.
Note: You can learn more about Request object and Response object here.
app.get("/", (req, res) => {
res.send("Hello World");
});
And we declare PORT and listen:
const PORT = process.env.PORT || 3000;
app.listen(PORT);
app.listen() starts and host a port.
In this example, we want to look for an environment variable called PORT. When we deploy, the server will check that first in the environment variable. If that is not available, we’ll run on 3000.
By default in development, we just need to enter the port number, and ExpressJs will automatically link to the localhost address.
In this example, we define the port number as 3000. For every request sent to the localhost address via port 3000, ExpressJs will catch it and process it.
We can also add a callback function to app.listen().
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server started on port ${3000}`));
The best practice for organizing the files:
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 the 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");