Express.js

Method Address Path

GET https://maxwell.sg:8888/menus/chicken-rice/8888

protocol Port

Backend input

→ ใส่ input ลงไป ต้องชัดเจน

Backend output

→ มันต้องตอบกลับได้

1xx: Informational
2xx: Success
3xx: Redirection
4xx: Client Error
5xx: Server Error

Node.js backend framework

in package.json ถ้าไม่อยากใช้ const express = require('express');

ให้เพิ่ม
"type":"module"

เช่น
{
  "name": "express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  },
  "type":"module"
}

เวลาใช้ จะกลายเป็นเหมือน react คือ import express from 'express';

URL

รำคาญมั้ยเวลาต้องนั่ง restart server 
เรามีตัวช่วย !! 'nodemon' https://www.npmjs.com/package/nodemon
npm install -g nodemon

nodemon index.js

หรือเพิ่ม "scripts": {
    "dev": "nodemon index.js",
  },

เวลาใช้ก็พิมพ์คำสั่ง npm run dev ได้เลย
index.js
//เอาข้าวมันไก่ 1 จาน
// GET http://localhost:8080/
//app.get('/', (request, response) => {}); จำ syntax 

app.get('/', (req, res) => {
    const chickenRice = {
        rice: 'olied rice',
        meat: 'boiled chicken',
        sauce: ['red', 'white'],
    };
		//default = 200 
    res.send(chickenRice); //ส่งข้าวมันไก่ออกไป
});


app.listen(8080, () => {
    console.log('Server is listening on port 8080');
});
node index.js
on http://localhost:8080/

{"rice":"olied rice","meat":"boiled chicken","sauce":["red","white"]}
on Postman
GET http://localhost:8080/ 

click SEND
//Status 200 OK
{
    "rice": "olied rice",
    "meat": "boiled chicken",
    "sauce": [
        "red",
        "white"
    ]
}
app.get('/', (req, res) => {
    const chickenRice = {
        rice: '',
        meat: 'boiled chicken',
        sauce: ['red', 'white'],
    };
    //default = 200
    //res.send(chickenRice); //ส่งข้าวมันไก่ออกไป
    //ถ้าข้าวหมด ของมันไม่มีแล้ว status 404 not found
    res.status(404).end(); //จำ syntax ไปเลย 
		//วิธีปิด res มี
		res.send();
    res.json();
});

on Postman
status 404 not found
// GET http://localhost:8080/chicken-rice
// GET http://localhost:8080/fried-chicken-rice

// ข้าวมันไก่ต้ม
app.get('/chicken-rice', (req, res) => {
    const chickenRice = {
        rice: 'olied rice',
        meat: 'boiled chicken',
        sauce: ['red', 'white'],
    };
		//default = 200
    res.send(chickenRice); 
});

//ข้าวมันไก่ทอด
app.get('/fried-chicken-rice', (req, res) => {
    const friedchickenRice = {
        rice: 'olied rice',
        meat: 'fried chicken',
        sauce: ['syrup', 'chili'],
    };
    //default = 200
    res.send(friedchickenRice); 
});

on Postman
http://localhost:8080/chicken-rice
{
    "rice": "olied rice",
    "meat": "boiled chicken",
    "sauce": [
        "red",
        "white"
    ]
}

http://localhost:8080/fried-chicken-rice
{
    "rice": "olied rice",
    "meat": "fried chicken",
    "sauce": [
        "syrup",
        "chili"
    ]
}

but http://localhost:8080/
404 not found

Parameter

app.get('/:menu', (req, res) => {  // ใช้ : (colon) 
    console.log('Request paramaeters');
    console.log(req.params);
    const chickenRice = {
        rice: 'olied rice',
        meat: 'boiled chicken',
        sauce: ['red', 'white'],
    };
    //default = 200
    res.send(chickenRice); 
});

//Request paramaeters
//{ menu: 'chicken-rice' }

on Postman
http://localhost:8080/chicken-rice
{
    "rice": "olied rice",
    "meat": "boiled chicken",
    "sauce": [
        "red",
        "white"
    ]
}
app.get('/:menu', (req, res) => {
    console.log('Request paramaeters');
    console.log(req.params);
    const { menu } = req.params;
    const chickenRice = {
        rice: 'olied rice',
    };
    if (menu === 'chicken-rice') {
				chickenRice.meat = 'boiled-chicken';
        chickenRice.sauce = ['red', 'white'];
    } else if (menu === 'fried-chicken-rice') {
        chickenRice.meat = 'fried chicken';
        chickenRice.sauce = ['syrup', 'chili'];
    }
    //default = 200
    res.send(chickenRice); 
});

on Postman
http://localhost:8080/chicken-rice
{
    "rice": "olied rice",
    "meat": "boiled-chicken",
    "sauce": [
        "red",
        "white"
    ]
}

http://localhost:8080/fried-chicken-rice
{
    "rice": "olied rice",
    "meat": "fried chicken",
    "sauce": [
        "syrup",
        "chili"
    ]
}
app.get('/:menu', (req, res) => {
    console.log('Request paramaeters');
    console.log(req.params);
		// const params = { menu: 'chicken-rice', 'sauce', 'pickle'};
    // const menu = params.menu;
		// const sauce = params.sauce
		// const pickle = params.pickle 
		// const { menu, sauce, pickle } = req.params;
    const { menu } = req.params;
    const chickenRice = {
        rice: 'olied rice',
    };
    if (menu === 'chicken-rice') {
        chickenRice.meat = 'boiled-chicken';
        chickenRice.sauce = ['red', 'white'];
        res.status(200).send(chickenRice); 
    } else if (menu === 'fried-chicken-rice') {
        chickenRice.meat = 'fried chicken';
        chickenRice.sauce = ['syrup', 'chili'];
        res.status(200).send(chickenRice); 
    } else {
        //400 Bad Request
        res.status(400).send(`We not serving ${menu}`)
    }
});

on Postman
http://localhost:8080/kaomoodang
We not serving kaomoodang
app.post('/:menu', (req, res) => {});//การสร้าง การเพิ่มข้อมูล จดกระดาษหน้าใหม่ บลาๆ เช่น ไปวิ่งมา 3 ชม 
app.put('/:menu', (req, res) => {}); //อัพเดทข้อมูล เช่น ลงไปแล้วว่าไปวิ่งมา 3 ชม แต่จะแก้ ออกเพิ่ม จาก 3 -> 4 ชม
app.delete ('/:menu', (req, res) => {}); //ลบข้อมูล
//อยากให้ลูกค้ามาสั่งล่วงหน้า
// POST /:menu 

const preOrders = [];

app.post('/pre-orders', (req, res) => { 
    const { menu } = req.params;
    const newPreorder = {
        id: preOrders.length,
        menu: menu,
    };
    preOrders.push(newPreorder);
    res.status(200).send(`Order success. Your order id ${newPreorder.id}`); 
});

on Postman
http://localhost:8080/chicken-rice
Order success. Your order id 0
//ลูกค้ายกเลิกออเดอร์
// DELETE /:menu 

app.delete('/pre-orders/:orderID', (req, res) => { 
    const { menu, orderID } = req.params;
    const newPreorderIndex = preOrders.findIndex((order) => order.id === order.id);
    if (newPreorderIndex === -1) { //ถ้าเป็น -1 คือ ไม่มีคำสั่ง order นี้ ยกเลิกไม่ได้
        return res.status(404).send(`Order ${orderID} not found`); 
    }
    preOrders[newPreorderIndex] = null
    res.status(200).send(`Order ${orderID} canceled`); 
});

on Postman
//post ก่อน (สร้างก่อน) สัก 5 order
http://localhost:8080/pre-orders/
Order success. Your order id 5
//ถ้าจะลบ order ที่ 3
//ส่งเป็น delete 
http://localhost:8080/pre-orders/3
Order 3 canceled

Query Parameter

http://localhost:8080/pre-orders/?menu=fried-chicken-rice&size=xl

ด้านหลัง ? ทั้งหมด จะเรียก Query Param
ในที่นี้คือ menu=fried-chicken-rice&size=xl
จะใช้ ตัว & ใน การแบ่ง
keyvalue
menufried-chicken-rice
sizexl
app.post('/pre-orders', (req, res) => { 
    const { menu, size } = req.query;
    console.log('Request query');
    console.log(req.query);
    const newPreorder = {
        id: preOrders.length,
        menu: menu,
    };
    preOrders.push(newPreorder);
    res.status(200).send(`Order success. Your order id ${newPreorder.id}`); 
});

Request query
{ menu: 'fried-chicken-rice', size: 'xl' }

Router

โดยปกติจะอยู่ใน folder routers
สร้างไฟล์ใหม่ขึ้นมา ชื่อ preOrder.js

ใน index.js
import { preOrdersRouter } from './routers/preOrder.js';

และเวลาต้องการจะประกอบร่าง
app.use(preOrdersRouter);

ใน preOrder.js
const preOrdersRouter = express.Router(); //อันนี้จำไปเลย ถ้าต้องการจะสร้าง router ตัวใหม่
ใน preOrder.js เขียนเหมือน app ทุกอย่างเลย แค่เปลี่ยนเป็น preOrdersRouter 

import express from 'express';
const preOrdersRouter = express.Router();

const preOrders = [];

// preOrdersRouter.get('/pre-orders:orderId', (req, res) => { 
// });

preOrdersRouter.post('/pre-orders', (req, res) => { 
    const { menu, size } = req.query;
    console.log('Request query');
    console.log(req.query);
    const newPreorder = {
        id: preOrders.length,
        menu: menu,
    };
    preOrders.push(newPreorder);
    res.status(200).send(`Order success. Your order id ${newPreorder.id}`); 
});

//ลูกค้ายกเลิกออเดอร์
// DELETE /:menu 

preOrdersRouter.delete('/pre-orders/:orderID', (req, res) => { 
    const { menu, orderID } = req.params;
    const newPreorderIndex = preOrders.findIndex((order) => order.id === order.id);
    if (newPreorderIndex === -1) { //ถ้าเป็น -1 คือ ไม่มีคำสั่ง order นี้ ยกเลิกไม่ได้
        return res.status(404).send(`Order ${orderID} not found`); 
    }
    preOrders[newPreorderIndex] = null
    res.status(200).send(`Order ${orderID} canceled`); 
});

export { preOrdersRouter }; //อย่าลืม export ไม่งั้น Index.js จะหาไม่เจอ
จะเห็นได้ว่า ตรง
preOrdersRouter.post('/pre-orders', (req, res) => { 
มี /pre-orders ยุบยับไปหมด เราลบออกได้นะ

แล้วใส่ path ตรง
app.use('/pre-orders', preOrdersRouter); แทน
คือให้ path pre-orders ทั้งหมดเนี่ย วิ่งเข้า preOrdersRouter โค้ดจะมีความเรียบร้อยขึ้น