MERN Stack શીખવાનો ૩૮મો દિવસ

હું મારી MERN stack સફરના ૩૮મા દિવસે છું.

ગઈકાલે મેં URL માંથી query strings કેવી રીતે મેળવવી તે શીખ્યું. આજે મેં HTTP request methods નો અભ્યાસ કર્યો.

સર્વરને યુઝરનો હેતુ (intent) જાણવાની જરૂર હોય છે. આ જાણવા માટે તમે req.method પ્રોપર્ટીનો ઉપયોગ કરો છો. આ પ્રોપર્ટી તમારા backend ને જણાવે છે કે કઈ ક્રિયા કરવાની છે.

એક endpoint વપરાયેલ method ના આધારે તેનું વર્તન બદલે છે.

અહીં મુખ્ય ચાર methods છે:

જ્યારે તમે આ methods ને endpoint સાથે મેપ કરો છો, ત્યારે તમારું backend કાર્યરત બને છે.

ઉદાહરણ કોડ:

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);

સ્ત્રોત: https://dev.to/ali_hamza_589ec7b3eb6688d/day-38-of-learning-mern-stack-opl