𝗗𝗮𝘆 𝟯𝟴 𝗼𝗳 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗠𝗘𝗥𝗡 𝗦𝘁𝗮𝗰𝗸
I am on day 38 of my MERN stack journey.
Yesterday I learned to extract query strings from URLs. Today I studied HTTP request methods.
A server needs to know the intent of a user. You use the req.method property to find this out. This property tells your backend what action to take.
An endpoint changes its behavior based on the method used.
Here are the four main methods:
- GET: Fetch or read data from the server.
- POST: Send or create new data on the server.
- PUT/PATCH: Update existing data.
- DELETE: Remove data from the server.
When you map these methods to an endpoint, your backend becomes functional.
Example code:
const http = require("http");
const server = http.createServer((req, res) => { if (req.url === "/api/data") { if (req.method === "GET") { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Reading records..."); } else if (req.method === "POST") { res.writeHead(201, { "Content-Type": "text/plain" }); res.end("Creating new data!"); } } else { res.end("Standard Route"); } });
server.listen(8000);
Source: https://dev.to/ali_hamza_589ec7b3eb6688d/day-38-of-learning-mern-stack-opl