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

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

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

આજ પહેલા સુધી, મારો સર્વર દરેક request ને એકસરખી રીતે લેતો હતો. હવે, હું યુઝરના હેતુ (intent) ના આધારે backend પાસે અલગ-અલગ ક્રિયાઓ કરાવી શકું છું. આ એક static endpoint ને functional tool માં બદલી નાખે છે.

મેં req.method property પર ધ્યાન કેન્દ્રિત કર્યું. આ property સર્વરને જણાવે છે કે client શું કરવા માંગે છે.

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

જ્યારે તમે req.method નો ઉપયોગ કરો છો, ત્યારે તમે તમારી એપ્લિકેશનના લોજિકને નિયંત્રિત કરો છો. યુઝર તે જ URL પર પેજ જુએ છે કે ફોર્મ સબમિટ કરે છે તેનો નિર્ણય તમે લો છો.

Code example:

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 database 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