← Back to Node.js Course | Chapter 6: HTTP Module | Lesson 2 of 7

Handling requests

The request object tells you the method, URL, headers and body of what the client sent.

In this page:

  1. Handling requests
Syntax
javascript
http.createServer((req, res) => {
  req.method;
  req.url;
  req.headers['header-name'];
});

Handling requests

req.method and req.url identify the action and path, req.headers holds lowercase header names, and the body arrives as a stream you read by listening to data and end. Branch on method and URL to route manually.

Note: Header names are lowercased in req.headers.

Example: Handling requests

javascript
const http = require("http");
const server = http.createServer((req, res) => {
  let body = "";
  req.on("data", (c) => (body += c));
  req.on("end", () => res.end(`${req.method} ${req.url} body=${body} ua=${req.headers["user-agent"] || "none"}`));
});
server.listen(0, () => {
  const r = http.request({ port: server.address().port, method: "POST", path: "/echo?x=1", headers: { "user-agent": "demo" } }, (res) => {
    res.on("data", (c) => console.log(String(c)));
    res.on("end", () => server.close());
  });
  r.end("hi");
});

// Output:
// POST /echo?x=1 body=hi ua=demo

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Forgetting the body is a stream
  2. Comparing headers with wrong case
  3. Not limiting body size
Chapter Summary
  • req.method and req.url route requests
  • Headers are lowercase
  • Body arrives as a stream
  • Limit body sizes
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.