Create an empty folder on your computer, run then run
npm install express
to install Express into the folder.
The first example we’re going to create is a simple Express Web Server.
Copy this code:
const express = require('express')
const app = express()
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(3000, () => console.log('Server ready'))
Save this to an index.js
file in your project root folder, and start the server using
node index.js
You can open the browser to port 3000 on localhost and you should see the Hello World!
message.
Those 4 lines of code do a lot behind the scenes.
First, we import the express
package to the express
value.
We instantiate an application by calling the express()
method.
Once we have the application object, we tell it to listen for GET requests on the /
path, using the get()
method.
There is a method for every HTTP verb: get()
, post()
, put()
, delete()
, patch()
:
app.get('/', (req, res) => { /* */ })
app.post('/', (req, res) => { /* */ })
app.put('/', (req, res) => { /* */ })
app.delete('/', (req, res) => { /* */ })
app.patch('/', (req, res) => { /* */ })
Those methods accept a callback function - which is called when a request is started - and we need to handle it.
We pass in an arrow function:
(req, res) => res.send('Hello World!')
Express sends us two objects in this callback, which we called req
and res
, they represent the Request and the Response objects.
Both are standards and you can read more on them here:
- https://developer.mozilla.org/en-US/docs/Web/API/Request
- https://developer.mozilla.org/en-US/docs/Web/API/Response
Request is the HTTP request. It gives us all the request information, including the request parameters, the headers, the body of the request, and more.
Response is the HTTP response object that we’ll send to the client.
What we do in this callback is to send the ‘Hello World!’ string to the client, using the Response.send()
method.
This method sets that string as the body, and it closes the connection.
The last line of the example actually starts the server, and tells it to listen on port 3000
. We pass in a callback that is called when the server is ready to accept new requests.