โดยรูปแบบการทำงานคือ ฝั่ง Client จะมีการส่งคำร้องขอไปยัง server โดยใช้คำสั่ง get, post, put, delete ส่วนฝั่ง server จะตอบข้อมูลกลับไปพร้อมสถานะของ HTTP เช่น หากไม่พบข้อมูลที่ร้องขอจากเครื่องแม่ข่าย จะขึ้นสถานะเป็น 404 Not found
ในส่วนของ method ที่ใช้บ่อย ๆ คือ
get สำหรับขอข้อมูล
post สำหรับเพิ่มข้อมูล
put สำหรับแก้ไขข้อมูล (ในบางแห่งอาจใช้ patch สามารถแก้ข้อมูลได้เช่นกัน)
delete สำหรับลบข้อมูล
รูปแบบการเขียน
ยกตัวอย่างการใช้ get
โค้ด: เลือกทั้งหมด
app.get('/get', function (req, res) {
console.log('data');
res.send(data);
});
res.send(data) จะเป็นการส่งค่า data ที่ได้มากลับไปยังไฟล์ที่เรียกใช้ API
ยกตัวอย่างการใช้ post
โค้ด: เลือกทั้งหมด
app.post("/add", async (req, res) => {
console.log('add data');
product: req.body.productName,
product.save().then(data => {
res.status(200).json(data);
});
});
ตัวอย่างการใช้ put
โค้ด: เลือกทั้งหมด
app.put("/edit", async (req, res) => {
const id = req.body._id;
Product.findByIdAndUpdate(id, {$set:req.body}, function(err, result){
if(err){
console.log(err);
}
console.log("RESULT: " + result);
});
res.send('Done')
res.status(200).json(data);
});
(***put กับ patch ใช้ในการแก้ไขข้อมูลเหมือนกัน ต่างกันตรงที่หากแก้ไขข้อมูลโดยใช้ put จะต้องใส่ข้อมูลเดิมที่ไม่ต้องการแก้ไขอีกครั้งด้วย แต่ patch จะแก้ไขข้อมูลใหม่โดยที่ข้อมูลเดิมยังอยู่)
ตัวอย่างการใช้ delete
โค้ด: เลือกทั้งหมด
app.delete("/del", (req, res, next) => {
const id = req.body._id;
console.log(id);
Product.findByIdAndDelete({ _id: id })
.then(result => {
res.status(200).json(result);
})
});
บทความที่เกี่ยวข้อง
การใช้ API ของไปรษณีย์ไทย
REST API คืออะไร
ข้อแตกต่างระหว่าง SOAP กับ REST
ทำความรู้จักกับ Node.js