Junior — Middle
What components make up an HTTP request and how do they interact?
sobes.tech AI
Answer from AI
An HTTP request consists of several main components:
-
Request Line — contains the request method (GET, POST, etc.), URL, and HTTP protocol version.
-
Headers — a set of key-value pairs that convey meta-information about the request, such as
Content-Type,Authorization,User-Agent. -
Body — an optional part containing data sent by the client to the server (e.g., form data or JSON in POST requests).
-
Empty line — separates headers from the body.
Interaction of components:
- The client forms the request line with the required method and URL.
- Adds necessary headers to describe the request.
- If needed, adds a body with data.
- Sends the request to the server.
Example of an HTTP request:
POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
Authorization: Bearer token123
{"name": "John", "age": 30}
In Node.js, IncomingMessage objects (for requests) and ServerResponse objects (for responses) are used to handle HTTP requests, allowing reading the request line, headers, and body.