𝗗𝗮𝘆 𝟯𝟳 𝗼𝗳 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗠𝗘𝗥𝗡 𝗦𝘁𝗮𝗰𝗸
I am on day 37 of my MERN stack journey.
Yesterday, I set up clean routing for pages like /about and /contact. Today, I focused on backend data communication. I studied URL parsing and query parameters.
When you search for products on a website, the site sends data through the URL. You often see extra text after a question mark in the address bar. This is query data.
I learned how to use the Node.js url module to read this data. The module turns a long URL string into a structured object.
Here is how the data breaks down:
- Pathname: This is the main location, such as /search or /api/products.
- Query: These are the key-value pairs after the question mark, like ?name=ali&id=7.
The url module makes this data easy to use in your code. It converts the string into a JavaScript object.
Example code:
const http = require("http"); const url = require("url");
const server = http.createServer((req, res) => { let parsedUrl = url.parse(req.url, true); let pathname = parsedUrl.pathname; let queryData = parsedUrl.query;
if (pathname === "/search") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Searching logs for user: ${queryData.name} with ID: ${queryData.id}`);
} else {
res.end("Standard Endpoint View");
}
}); server.listen(8000);
Learning to parse URLs helps you build dynamic websites. You can now capture user input directly from the web address.
Source: https://dev.to/ali_hamza_589ec7b3eb6688d/day-37-of-learning-mern-stack-4758