Building Your First Web Server
A web server is a program that listens for HTTP requests on a network port and sends back responses, such as HTML pages or JSON data. With Express, a small framework on top of Node.js, you can build one in about ten lines. This first server is the foundation for everything that follows: REST APIs, form handling, authentication and serving a React app all start with the same setup.
Setting up the project
Create a folder, initialise it as a Node project and install Express. The -y flag accepts the default answers for package.json.
mkdir my-server
cd my-server
npm init -y
npm install express
node index.js # after creating the file below
The server code, line by line
Create index.js in the same folder:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.get('/api/time', (req, res) => {
res.json({ now: new Date().toISOString() });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
require('express')loads the library, and callingexpress()creates the application object.app.get(path, handler)registers a route: when a GET request arrives for that path, Express calls the handler.- The handler receives
req, the incoming request with details like the URL, headers and query string, andres, the object you use to reply. res.send()sends text or HTML and sets a suitable content type.res.json()converts a JavaScript object to JSON and sets theapplication/jsonheader.app.listen(port)starts the server and keeps the Node process running, waiting for requests.
Reading the port from process.env.PORT means hosting platforms can choose the port for you, while you still get 3000 on your own machine.
Trying it out
Open http://localhost:3000 in a browser and you should see the greeting. Visit /api/time to see JSON. Any other path returns Express's default "Cannot GET" page with a 404 status, because no route matches. From a terminal, curl http://localhost:3000/api/time shows the same response, which is useful once you start testing POST and PUT requests that a browser address bar cannot send.
How this compares with Node's built-in http module
Node can create a server without Express using http.createServer(). You would then have to check req.url and req.method manually for every route, set headers yourself, and parse request bodies by hand. Express handles routing, response helpers and middleware, so you write the logic that matters instead of plumbing.
Problems you will likely run into
Changes do not appear. Node loads your file once when it starts. After editing index.js, you must stop the server with Ctrl + C and start it again. The next lesson introduces Nodemon to restart automatically; recent Node versions also offer node --watch index.js.
EADDRINUSE error. This means another program, often an earlier copy of your server still running in another terminal, is already using port 3000. Close it or change the port.
The browser keeps loading forever. Every request must end with a response. If a handler forgets to call res.send(), res.json() or similar, the browser waits until it times out. Equally, sending two responses in one handler causes the "Cannot set headers after they are sent" error.
What you built
You created an Express app, registered two GET routes, replied with text and JSON, and started listening on a configurable port. Every Express project, however large, grows from these same pieces.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.