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

HTTP methods

GET, POST, PUT, PATCH and DELETE tell the server what kind of action you want.

In this page:

  1. HTTP methods

HTTP methods

GET reads data, POST creates, PUT replaces, PATCH partially updates and DELETE removes. Servers branch on req.method. GET and DELETE are typically without a body, and safe or idempotent semantics matter for retries.

Note: GET must never change data.

Example: HTTP methods

javascript
const http = require("http");
const items = ["a"];
const server = http.createServer((req, res) => {
  if (req.method === "GET") return res.end(JSON.stringify(items));
  if (req.method === "POST") { items.push("new"); res.statusCode = 201; return res.end("created"); }
  res.statusCode = 405; res.end("method not allowed");
});
server.listen(0, async () => {
  const base = "http://localhost:" + server.address().port;
  console.log((await fetch(base)).status, await (await fetch(base)).text());
  console.log((await fetch(base, { method: "POST" })).status);
  console.log((await fetch(base, { method: "DELETE" })).status);
  server.close();
});

// Output:
// 200 ["a"]
// 201
// 405

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

Related Topics
Common Mistakes
  1. Using GET to change data
  2. Not returning 405 for unsupported methods
  3. Confusing PUT and PATCH
Chapter Summary
  • GET reads
  • POST creates
  • PUT replaces, PATCH updates
  • DELETE removes
🔒

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.