Start an HTTP service
Run a conventional Express web application on a TCP port.
Express.js · Module
Starts an Express application listening for incoming HTTP connections. It is a convenience wrapper around Node.js HTTP server listening and returns the underlying server.
app.listen() creates an HTTP server for the Express application and delegates listening to Node.js with the supplied arguments. It starts accepting connections on the selected port or host and returns the underlying server object, which can be monitored or controlled with Node.js APIs.
app.listen([port[, host[, backlog]]][, callback])| Name | Type | Description |
|---|---|---|
...args | Node.js listen arguments | Arguments accepted by Node.js Server.listen(), commonly a port and optional callback; a host may also be supplied. |
A Node.js HTTP server returned by the underlying server.listen() call.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello world');
});
const server = app.listen(3000, () => {
console.log('Listening on port 3000');
});
server.on('error', console.error);Creates an Express app, registers a route, and starts listening for HTTP connections on port 3000. The returned server can be used with Node.js server APIs.
Run a conventional Express web application on a TCP port.
Retain access to Node.js server events and controls after startup.
Reuse the same Express application with separately created HTTP and HTTPS servers.
app.listen() is Express's convenience wrapper around Node's HTTP server. It creates a server with the Express application as its request handler and invokes the server's listen method with the provided arguments.
Follow-up: How would you serve HTTPS? Create an HTTPS server explicitly with https.createServer(options, app), then call listen on that server.
The port argument identifies where the application accepts connections, such as 3000. The optional callback runs after the server begins listening, while the returned server exposes Node.js server functionality.
Follow-up: How can startup failures be handled? Attach an error listener to the returned server and handle events such as a port already being in use.
An Express application is callable as a request handler, so Node's HTTP server can dispatch incoming requests to it. This lets the same application be passed directly to HTTP or HTTPS server constructors.
Follow-up: Why avoid app.listen() for HTTPS? app.listen() constructs an HTTP server, so HTTPS requires explicitly constructing the HTTPS server with TLS options.
express()app.use()app.get()http.createServer()https.createServer()