HTTP methods
GET, POST, PUT, PATCH and DELETE tell the server what kind of action you want.
In this page:
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
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
- Using GET to change data
- Not returning 405 for unsupported methods
- 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: