To implement Express as the HTTP server for a Node.js application, you need to create an instance and begin listening on a port. The following three lines of code start a very rudimentary Express server listening on port 8080:
var express = require('express'),
var app = express();
app.listen(8080);
The app.listen(port)
call binds the underlying HTTP connection to the port
and begins listening on it. The underlying HTTP connection is the same connection produced using the listen()
method on a Server
object created using the http
library discussed in Chapter 7 “Implementing HTTP Services in Node.js.”
In fact, the value returned by express()
is actually a callback function that maps to the callback function that is passed to the http.createServer()
and https.createServer()
methods.
Listing 18.1 shows how to implement a basic HTTP and HTTPS server using Node.js. Notice that the app
variable that express()
returns is passed into the createServer()
methods. Also, notice that an options
object is defined to set the host
, key
, and cert
used to create the HTTPS server. Lines 13–15 implement a simple get
route that handles the /
path.
01 var express = require('express'),
02 var https = require('https'),
03 var http = require('http'),
04 var fs = require('fs'),
05 var app = express();
06 var options = {
07 host: '127.0.0.1',
08 key: fs.readFileSync('ssl/server.key'),
09 cert: fs.readFileSync('ssl/server.crt')
10 };
11 http.createServer(app).listen(80);
12 https.createServer(options, app).listen(443);
13 app.get('/', function(req, res){
14 res.send('Hello from Express'),
15 });