You'll need node >= 4
and express 4
for this project. You can get the latest node
distribution from their download page.
Before this tutorial, you should initialize your node project by running
$ npm init
from the command line and filling in the information you want. Note that you can change the info at any time by editing the package.json
file.
Install express
with npm
:
$ npm install --save express
After installing Express as a node module, we can create our entry point. This should be in the same directory as our package.json
$ touch app.js
The folder should have the following directory structure:
<project_root>
|-> app.js
|-> node_modules/
'-> package.json
Open app.js
in your preferred editor and follow these four steps to create your first Express app:
// 1. Import the express library.
import express from 'express';
// 2. Create an Express instance.
const app = express();
// 3. Map a route. Let's map it to "/", so we can visit "[server]/".
app.get('/', function(req, res) {
res.send('Hello World');
});
// 4. Listen on port 8080
app.listen(8080, function() {
console.log('Server is running on port 8080...');
});
From the project directory, we can run our server using the command
$ node app.js
You should see the text
$ Our Express App Server is listening on 8080...
Now, visit http://localhost:8080/
and you'll see the text "Hello World!"
Congratulations, you've created your first Express app!