MERN Stack ਸਿੱਖਣ ਦਾ 38ਵਾਂ ਦਿਨ

ਮੈਂ ਆਪਣੀ MERN stack ਯਾਤਰਾ ਦੇ 38ਵੇਂ ਦਿਨ 'ਤੇ ਹਾਂ।

ਕੱਲ੍ਹ ਮੈਂ URLs ਤੋਂ query strings ਕੱਢਣਾ ਸਿੱਖਿਆ। ਅੱਜ ਮੈਂ HTTP request methods ਦਾ ਅਧਿਐਨ ਕੀਤਾ।

ਇੱਕ ਸਰਵਰ ਨੂੰ ਯੂਜ਼ਰ ਦੇ ਮਕਸਦ (intent) ਬਾਰੇ ਜਾਣਨ ਦੀ ਲੋੜ ਹੁੰਦੀ ਹੈ। ਇਸਦਾ ਪਤਾ ਲਗਾਉਣ ਲਈ ਤੁਸੀਂ req.method property ਦੀ ਵਰਤੋਂ ਕਰਦੇ ਹੋ। ਇਹ property ਤੁਹਾਡੇ backend ਨੂੰ ਦੱਸਦੀ ਹੈ ਕਿ ਕਿਹੜਾ ਕੰਮ ਕਰਨਾ ਹੈ।

ਇੱਕ endpoint ਵਰਤੇ ਗਏ method ਦੇ ਅਧਾਰ 'ਤੇ ਆਪਣਾ ਵਿਵਹਾਰ ਬਦਲਦਾ ਹੈ।

ਇੱਥੇ ਚਾਰ ਮੁੱਖ methods ਹਨ:

ਜਦੋਂ ਤੁਸੀਂ ਇਹਨਾਂ methods ਨੂੰ ਇੱਕ endpoint ਨਾਲ ਮੈਪ ਕਰਦੇ ਹੋ, ਤਾਂ ਤੁਹਾਡਾ backend ਕਾਰਜਸ਼ੀਲ ਹੋ ਜਾਂਦਾ ਹੈ।

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