วันที่ 38 ของการเรียนรู้ MERN Stack

ผมกำลังอยู่ในวันที่ 38 ของการเดินทางเรียนรู้ MERN stack

เมื่อวานผมเรียนรู้วิธีการดึง query strings ออกจาก URL ส่วนวันนี้ผมได้ศึกษาเรื่อง HTTP request methods

เซิร์ฟเวอร์จำเป็นต้องทราบความต้องการของผู้ใช้ คุณสามารถใช้ property req.method เพื่อตรวจสอบเรื่องนี้ ซึ่ง property นี้จะบอก backend ว่าต้องดำเนินการอย่างไร

Endpoint จะเปลี่ยนพฤติกรรมตาม method ที่ถูกใช้งาน

นี่คือ 4 method หลัก:

เมื่อคุณจับคู่ method เหล่านี้เข้ากับ 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