Sub topic 5
HTTP requests and responses
HTTP (HyperText Transfer Protocol) is the text-based language a client and a server use to exchange resources over a connection. This chapter assumes you know what a URL is, that DNS turns a hostname into an IP address, and that TCP gives you a reliable byte stream between two machines. It also assumes you can run commands in a terminal. Here you will learn the exact shape of a request and a response, how a receiver finds where each message ends, and which mistakes cause most parsing problems.
The shape of a message
Every HTTP/1.1 message has the same layout:
- A start line. In a request it is the request line. In a response it is the status line.
- Zero or more header lines, each in the form
Name: value. - A blank line that ends the headers.
- An optional body.
Each line ends with CRLF, which is the two bytes carriage return (\r) and line feed (\n). The blank line is therefore a bare CRLF. This detail matters because the receiver uses that blank line to decide where headers stop and the body starts.
The request
A minimal request looks like this:
GET /index.html HTTP/1.1
Host: example.com
Accept: text/html
On the wire, each line ends in \r\n, and the message ends with an empty line:
GET /index.html HTTP/1.1\r\nHost: example.com\r\nAccept: text/html\r\n\r\nThe request line
The request line has three parts separated by single spaces.
| Part | Example | Meaning |
|---|---|---|
| Method | `GET` | The action the client wants. Methods get their own chapter. |
| Request target | `/index.html` | The path and query string, not the full URL. |
| Version | `HTTP/1.1` | The protocol version the client speaks. |
The request target usually holds only the path and query, such as /search?q=http. The scheme and host are not repeated here. The host goes in a header instead.
The Host header
HTTP/1.1 requires a Host header. A single IP address and port can serve many websites. The TCP connection carries no hostname, so the server needs Host to decide which site the request is for. A server should answer an HTTP/1.1 request without Host with 400 Bad Request.
Other request headers
The Accept header tells the server which content types the client prefers. Other common request headers include User-Agent, Accept-Language, Cookie, and Authorization. Headers get their own chapter. For now, remember that they are metadata about the request, and that header names are case-insensitive.
The response
A server answers with a response. Here is a small one:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 14
<h1>Hello</h1>The first line is the status line. It has the version, a three-digit status code, and a reason phrase (OK). Clients act on the code, not the phrase. Over the wire, the status line and every header end in \r\n, and an empty line separates the headers from the body.
The headers here describe the body. Content-Type says it is HTML encoded as UTF-8. Content-Length says it is 14 bytes long. You can check that: <h1>Hello</h1> is 4 + 5 + 5 = 14 characters, and each is one byte in UTF-8.
Knowing where a message ends
A TCP connection is a stream of bytes with no built-in message boundaries. After reading the headers, the receiver must work out how many body bytes to read. HTTP/1.1 gives it three ways to do this.
| Method | How it works | Typical use |
|---|---|---|
| `Content-Length` | The header states the body size in bytes. | Bodies whose size is known up front. |
| `Transfer-Encoding: chunked` | The body is sent as chunks, each prefixed with its size, ending with a zero-size chunk. | Generated or streamed output of unknown length. |
| Connection close | The server closes the connection to mark the end. | Old or simple servers. The client cannot tell a clean end from a failure. |
Requests with no body, such as a typical GET, have neither Content-Length nor Transfer-Encoding, and the blank line ends the message.
Connection reuse
HTTP/1.1 keeps the TCP connection open by default after a response (this is called keep-alive). The client can send another request on the same connection and skip the cost of a new TCP handshake. Reliable message framing is what makes this possible. If the receiver misjudges the length of one body, every later message on that connection is read from the wrong position.
Statelessness
Each request stands alone. The server does not need to remember earlier requests to understand the current one. Anything the server must know, such as who you are, has to be carried in the request, for example in a header. The cookies chapter shows how this works in practice.
Seeing real messages with curl
Run curl with -v (verbose) to see the exchange your browser performs:
curl -v https://example.com/In the output, lines that start with > are sent by curl, and lines that start with < are received. Lines that start with * are curl's own notes about the connection. You will see the request line, the headers curl added (Host, User-Agent, Accept), then the status line and response headers. The body prints after them.
To see only the response headers, use a HEAD request:
curl -I https://example.com/Producing messages in code
A server reads the method and path from the request and writes a status, headers, and a body. This small Node.js server shows all three:
import { createServer } from "node:http";
const server = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(`You requested ${req.method} ${req.url}\n`);
});
server.listen(3000);Save it as server.mjs, run node server.mjs, then in another terminal run curl -v http://localhost:3000/hello?x=1. The body will read You requested GET /hello?x=1. Node sets Content-Length for you here because res.end receives the whole body at once. If you write the body in several pieces, Node uses chunked encoding instead.
From the client side, the browser fetch API sends a request and exposes the parts of the response:
const response = await fetch("https://example.com/");
console.log(response.status);
console.log(response.headers.get("content-type"));
const html = await response.text();response.status is the status code. response.headers.get reads a header by name. response.text() reads the body, and it returns a promise because the body may still be arriving.
Common errors
- Missing blank line. If a hand-written request does not end with an empty line, the server keeps waiting for more headers and the request appears to hang.
- Wrong
Content-Length. A value that is too small truncates the body and leaves leftover bytes that the next message on the connection will misread. A value that is too large makes the receiver wait for bytes that never arrive. - Missing
Host. An HTTP/1.1 server may reject the request outright, or it may serve the wrong site. - Wrong
Content-Typeor charset. The bytes arrive intact, but the client decodes them incorrectly. Text with accents turns into garbled characters. - Treating the reason phrase as data.
200 OKand200 Finemean the same thing. Always branch on the numeric code. - Line endings. The specification requires CRLF. Many servers tolerate a bare LF, but relying on that is fragile, and mismatches in how two systems parse a message are a known source of security bugs.
Try it by hand
You can speak HTTP without any tool that hides the details. With nc (netcat) installed, send a request to a plain-text HTTP port:
printf 'GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n' | nc example.com 80Connection: close asks the server to close the connection after responding, so nc exits when the response is done. Many sites reply to port 80 with a redirect to HTTPS, which is itself a useful thing to read. The status line will show a 301 or 308 code and a Location header.
Exercise
A response has the headers Content-Type: text/plain and Content-Length: 5, followed by the body Hello, world. What will a client that follows the specification read as the body, and what problem does this create on a reused connection?
Show answer
The client reads exactly 5 bytes, Hello. The remaining bytes, , world, stay in the stream. On a reused connection the client treats them as the start of the next response, which fails to parse as a status line and corrupts every later exchange on that connection.
Exercise
Why does an HTTP/1.1 request need a Host header even though the client has already connected to the server's IP address?
Show answer
Many websites can share one IP address and port, and the TCP connection does not carry the hostname. The server uses Host to decide which site the request is for.
Exercise
You write fetch("https://example.com/missing") and the server responds with 404 Not Found. Does the promise reject? How do you detect the failure?
Show answer
No. The promise resolves because a complete HTTP response arrived. Detect the failure by checking response.ok (false for codes outside 200 to 299) or by reading response.status.