In this section, you’ll develop a minimal Hello World application using Express to cover the basics, then we’ll move on to something more substantial. Since this project will be short-lived, we won’t bother with creating a package.json file.
To begin, create a directory called hello to hold the application, and open a terminal to this directory. Next, install Express and Morgan (a logging utility).
| | $ npm install express@4.14.1 morgan@1.8.1 |
With those modules installed, open a text editor and enter the following:
| | 'use strict'; |
| | const express = require('express'); |
| | const morgan = require('morgan'); |
| | |
| | const app = express(); |
| | |
| | app.use(morgan('dev')); |
| | |
| | app.get('/hello/:name', (req, res) => { |
| | res.status(200).json({'hello': req.params.name}); |
| | }); |
| | |
| | app.listen(60701, () => console.log('Ready.')); |
Save this file as server.js in your hello project directory. First, this program brings in the Express module and the Morgan module. Morgan provides HTTP request logging.
Like the Request module we worked with in the last chapter, the Express module is itself a function. When you call this function, Express creates an application context for you. By strong convention, we name this variable app.
Express functionality is provided through middleware, which are functions that manipulate the request and response objects. To specify middleware for your app, you call app.use(), passing in the middleware you want. In our case, we’re using the morgan middleware set to dev mode, which will log to the console all requests coming in.
Next we use app.get() to tell Express how we want to handle HTTP GET requests to the /hello/:name path. The :name chunk in the path is called a named route parameter. When the API is hit, Express will grab that part of the URL and make it available in req.params.
In addition to get(), Express has put(), post(), and delete() methods to register handlers for HTTP PUT, POST, and DELETE requests, respectively. In our case, we tell the response object, res, to send back as JSON an object whose hello key is set to the name parameter.
Finally, this program listens on TCP port 60701 for incoming HTTP requests, and logs a message to the console when it’s ready to receive connections. Let’s run the app to see what it does.
Open a terminal to the hello directory and run node server.js.
| | $ node server.js |
| | Ready. |
With the Hello server running, let’s try it out in a separate terminal using curl, an extremely useful off-the-shelf command-line program for issuing HTTP requests.
Most popular operating systems come with curl bundled in, but if yours doesn’t, pause here and install it. We’ll be using curl frequently in this chapter to try out our various APIs.
Now, try hitting the /hello/:name path with curl, supplying your own name in the URL.
| | $ curl -i localhost:60701/hello/jimbo |
| | HTTP/1.1 200 OK |
| | X-Powered-By: Express |
| | Content-Type: application/json; charset=utf-8 |
| | Content-Length: 17 |
| | ETag: W/"11-vrDYB0Rw9smBgTMv0r99rA" |
| | Date: Tue, 14 Feb 2017 10:34:13 GMT |
| | Connection: keep-alive |
| | |
| | {"hello":"jimbo"} |
Adding the -i flag tells curl that it should output the HTTP headers in addition to the response body. Note that the HTTP response code was 200 OK, as expected.
Back in the server terminal, you should see something like this (thanks to the Morgan middleware):
| | GET /hello/jimbo 200 3.013 ms - 17 |
By default, curl will display information in the terminal describing the progress of the request. This is useful for large requests, but it can be distracting for smaller requests, especially when you intend to pipe the response into another program, such as jq. To disable this progress output, use the -s flag, meaning silent.
| | $ curl -s localhost:60701/hello/jimbo | jq '.' |
| | { |
| | "hello": "jimbo" |
| | } |
Now that we’ve got the basic outline of an Express REST/JSON service under control, let’s build something with a bit more bite to it.