Assuming you’ve already installed Node.js, create a directory to hold your application, and make that your working directory.
$ mkdir myapp
$ cd myapp
Use the npm init command to create a package.json file for your application. For more information on how package.json works:
$ npm init
This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
entry point: (index.js)
Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the suggested default file name.
Now install Express in the myapp directory and save it in the dependencies list. For example:
$ npm install express --save
To install Express temporarily and not add it to the dependencies list:
$ npm install express --no-save
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost: ${port}`)
)
This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.
Running Locally
First create a directory named myapp, change to it and run npm init. Then install express as a dependency, as per the installation guide.
In the myapp
directory, create a file named app.js
and copy in the code from the example above.
Run the app with the following command:
node app.js
Then, load http://localhost:3000/
in a browser to see the output.
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
Each route can have one or more handler functions, which are executed when the route is matched.
Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
Where:
app
is an instance ofexpress
.METHOD
is an HTTP request method, in lowercase.PATH
is a path on the server.HANDLER
is the function executed when the route is matched.
The following examples illustrate defining simple routes.
Respond with Hello World!
on the homepage:
app.get('/', function (req, res) {
res.send('Hello World!')
})
Respond to POST request on the root route (/), the application’s home page:
app.get('/', function (req, res) {
res.send('Got a POST request')
})
Respond to a PUT request to the /user
route:
app.get('/user', function (req, res) {
res.send('Got a PUT request at /user')
})
Respond to a DELETE request to the /user
route:
app.get('/user', function (req, res) {
res.send('Got a DELETE request at /user')
})
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
The function signature is:
express.static(root, [options])
The root argument specifies the root directory from which to serve static assets.
For example, use the following code to serve images, CSS files, and JavaScript files in a
directory
named public
app.use(express.static('public'))
Now, you can load the files that are in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
To use multiple static assets directories, call the express.static
middleware function multiple times:
app.use(express.static('public'))
app.use(express.static('files'))
Express looks up the files in the order in which you set the static directories with the express.static
middleware function.
To create a virtual path prefix (where the path does not actually exist in the file system) for
files
that are served by the express.static
function, specify a mount
path
for the static directory, as shown below:
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:
app.use('/static', express.static(path.join(__dirname, 'public')))
Middleware functions are functions that have access to the request object (req
), the response object (res
), and
the
next function in the application’s request-response cycle. The next function is a function in
the
Express router which, when invoked, executes the middleware succeeding the current middleware.
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
Starting with Express 5, middleware functions that return a Promise will call next(value)
when they reject or throw an error. next
will be called with either the rejected value or the thrown
Error.
Example: Middleware function myLogger
Here is a simple example of a middleware function called “myLogger”. This function just prints
“LOGGED” when a request to the app passes through it. The middleware function is assigned to a
variable named myLogger
.
To load the middleware function, call app.use()
, specifying the
middleware function. For example, the following code loads the myLogger
middleware function before the route to the root path (/).
const express = require('express')
const app = express()
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000)
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
Some popular template engines that work with Express are Pug, Mustache, and EJS. The Express application generator uses Jade as its default, but it also supports several others.
To render template files, set the following application setting properties, set in app.js in the default app created by the generator:
views
, the directory where the template files are located. Eg:app.set('views', './views')
. This defaults to the views directory in the application root directory.view engine
, the template engine to use. For example, to use the Pug template engine:app.set('view engine', 'pug')
.
Then install the corresponding template engine npm package; for example to install Pug:
$ npm install pug --save
After the view engine is set, you don’t have to specify the engine or load the template engine module in your app; Express loads the module internally, as shown below (for the above example).
app.set('view engine', 'pug')
Create a Pug template file named index.pug in the views directory, with the following content:
html
head
title= title
body
h1= message
Then create a route to render the index.pug file. If the view engine property is not set, you must specify the extension of the view file. Otherwise, you can omit it.
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'})
})
When you make a request to the home page, the index.pug file will be rendered as HTML.