"Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications."
Installation
In the terminal, we'll create and navigate to a folder that will host our server - we're using a folder named my_server
located in the home directory:
mkdir ~/my_server
cd ~/my_server
Next step is to initialise your application:
npm init -y
We'll also create the file that will act as the entry point:
touch index.js
To add Express
to our app, we'll run the following in the terminal:
npm install express --save
A Simple Server
We'll add a single endpoint that will display a simple "90-10.dev" message. Update index.js
as follows:
const express = require('express');
const app = express();
const port = 9010;
app.get('/', (req, res) => {
res.send('Welcome to 90-10.dev');
});
app.listen(port, () => {
console.log(`Server started at http://localhost:${port}`);
});
Run
Assuming an index.js
file in your current path:
node index.js
Now, if you point our browsers to http://localhost:9010, we'll see a webpage containing the 'Welcome to 90-10.dev' message.
Avoid relaunch
One of the limitations we're going to encounter, is the need to relauch it if changes are afflicted to the source file.
A great utility to overcome this limitation is nodemon
. To install it please run the following:
npm install -g nodemon
Launching the server will now be done by replacing node
with nodemon
:
nodemon index.js
Templating engines
Express supports a lot of templating engines - we're going to use one called pug
. To add it to our app:
npm install pug --save
Integrate
Next, we'll integrate it into our app inside index.js
- here is the top of it:
const express = require('express');
const app = express();
const port = 9010;
app.set('view engine', 'pug');
app.set('views','./views');
...
Views
You'll notice above that we're going to use a folder named views
to store our pug
templates. Let's create it together with a index.pug
file inside:
mkdir views
touch views/index.pug
First template
Let's add our first view - update views/index.pug
:
doctype html
html
head
title = "90-10.dev"
body
p Welcome to 90-10.dev
Using the template
Back in index.js
, let's make use of the new template - the file is listed in its entirety below:
const express = require('express');
const app = express();
const port = 9010;
app.set('view engine', 'pug');
app.set('views','./views');
app.get('/', (req, res) => {
res.render('index');
});
app.listen(port, () => {
console.log(`Server started at http://localhost:${port}`);
});
Relaunch the server
nodemon index.js
The reloaded webpage, http://localhost:9010, will now contain HTML as per the template - the noticeable difference is the browser window title now showing: '90-10.dev'.
What next?
The Express website has lots of good resources, amonst them the API reference.
Top comments (0)