Basic

Your first web server

A web server is a program that listens for requests and answers them with HTML. In this lesson you write the smallest possible Express server that prints "Hello" in your browser, the seed of everything you will build.

About 2 min of reading

Data Flow

A browser sends a request to the server, the server runs handler code, and replies with HTML that the browser renders.
1 User opens http://localhost:3000
↓
2 Browser sends a GET request to port 3000
↓
3 Express receives the request on the '/' route
↓
4 The handler calls res.send() with the answer
↓
5 The server returns the text as the HTTP response
↓
6 The browser displays the text
Why this works
What is a web server, really

A web server is just a program that is always running and always listening.

  • A browser (Chrome, Firefox) sends an HTTP request like GET /.
  • The server reads it, does something, and sends back an HTTP response with HTML, JSON, or other data.
  • The browser turns that HTML into the page you see.

Node.js is the engine that runs your JavaScript outside the browser. Express is a small library that makes writing servers easy. Together they are the most common stack for modern web apps.

Examples

Hello, browser

The fastest way to see a server run is to install Node.js, then create a folder and a single file called server.js.

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, browser!');
});

app.listen(3000, () => console.log('Running on http://localhost:3000'));

Then run:

node server.js

Open http://localhost:3000 in your browser. You should see Hello, browser!. That is a complete web application, the smallest one in the world for the moment, but complete.

The request / response cycle

Every web page you have ever loaded worked exactly like this. Something in your browser made a request to a computer somewhere, and that computer sent back a response.

app.get('/', (req, res) => {
  // req = what the browser asked for
  // res = what we send back
  res.send('Hello!');
});

The arrow function (req, res) => { ... } is the heart of a server. req (request) holds the incoming ask. res (response) is how you reply. You write logic between them, then tell the browser what to show.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

Next Lesson
Project setup with npm
Project setup with npm →