iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0
自我挑戰組

利用 node.js/express 架設網站系列 第 7

Day-07 express API開發(上)

  • 分享至 

  • xImage
  •  

今天的重點會是API開發,會有三個大重點:
1.了解RESTful API
2.創建CRUD API
3.基本身份驗證

了解RESTful API

RESTful API是目前網路應用程式最常用的設計模式。它基於HTTP協議,通過不同的HTTP方法對資源進行操作。
HTTP 方法:

  • GET: 用來獲取資源。
  • POST: 用來創建新資源。
  • PUT: 用來更新現有資源。
  • DELETE: 用來刪除資源。

RESTful API 的設計:
在設計 RESTful API 時,每個資源(如用戶、文章等)應該對應一個 URL 路徑。資源的操作則通過不同的 HTTP 方法完成。

創建CRUD API

接下來我將使用express創建一個簡單的CRUD API
CRUD代表的是:Create, Read, Update, Delete

  • 創建路由:
    • GET /users:獲取所有使用者
    • GET /users/:id:根據ID獲取單個使用者
    • POST /users:創建新使用者
    • PUT /users:id:更新使用者資料
    • DELETE /users/:id:刪除使用者
      範例:
const express = require('express');
const app = express();
app.use(express.json()); // 解析 JSON 請求

let users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Doe' }
];

// GET 所有用戶
app.get('/users', (req, res) => {
    res.json(users);
});

// GET 單個用戶
app.get('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).send('User not found');
    res.json(user);
});

// POST 新增用戶
app.post('/users', (req, res) => {
    const newUser = {
        id: users.length + 1,
        name: req.body.name
    };
    users.push(newUser);
    res.status(201).json(newUser);
});

// PUT 更新用戶
app.put('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).send('User not found');

    user.name = req.body.name;
    res.json(user);
});

// DELETE 刪除用戶
app.delete('/users/:id', (req, res) => {
    const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
    if (userIndex === -1) return res.status(404).send('User not found');

    users.splice(userIndex, 1);
    res.status(204).send(); // 204 表示 No Content
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});

這個 API 可以處理使用者的增、刪、改、查操作,並返回對應的 HTTP 狀態碼(如 201 表示創建成功,404 表示資源未找到)。

使用 JWT 進行身份驗證

JWT 是一個用來在客戶端和伺服器之間安全傳遞身份信息的標準。每個 JWT 包含一個加密的 token,用戶在登錄後獲取 token,並在後續請求中將其作為身份標識傳遞。

  • 安裝所需模組:
    npm install jsonwebtoken bcryptjs
    
  • 創建簡單的身份驗證系統:
    const jwt = require('jsonwebtoken');
    const bcrypt = require('bcryptjs');
    
    const users = [];
    
    // 註冊
    app.post('/register', async (req, res) => {
        const hashedPassword = await bcrypt.hash(req.body.password, 10);
        const newUser = {
            id: users.length + 1,
            name: req.body.name,
            password: hashedPassword
        };
        users.push(newUser);
        res.status(201).json(newUser);
    });
    
    // 登錄
    app.post('/login', (req, res) => {
        const user = users.find(u => u.name === req.body.name);
        if (!user) return res.status(404).send('User not found');
    
        bcrypt.compare(req.body.password, user.password, (err, isMatch) => {
            if (!isMatch) return res.status(401).send('Invalid credentials');
    
            const token = jwt.sign({ id: user.id }, 'secretKey', { expiresIn: '1h' });
            res.json({ token });
        });
    });
    
    // 驗證 Token 的中介軟體
    const authenticateToken = (req, res, next) => {
        const token = req.headers['authorization'];
        if (!token) return res.status(403).send('Token required');
    
        jwt.verify(token, 'secretKey', (err, user) => {
            if (err) return res.status(403).send('Invalid token');
            req.user = user;
            next();
        });
    };
    
    // 受保護的路由
    app.get('/protected', authenticateToken, (req, res) => {
        res.send('You are accessing a protected route!');
    });
    
    app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
    });
    
    這個範例展示了如何註冊、登入用戶,並使用 JWT 來保護某些路由。
    實際操作畫面:
    • 註冊用戶:
      因為瀏覽器無法發送post請求,所以我使用postman來操作。
      註冊成功的畫面:
      https://ithelp.ithome.com.tw/upload/images/20240920/201694653UHmKaE1lQ.png
      註冊成功之後換到登錄的路由:
      https://ithelp.ithome.com.tw/upload/images/20240920/20169465yFC35iUKiY.png
      登入成功之後會拿到一個token,使用這個token放在標頭並且送出請求,伺服器就會回應登入成功。
      https://ithelp.ithome.com.tw/upload/images/20240920/20169465n8GKSjXaJ3.png

上一篇
Day-06 處理靜態文件和連接資料庫
下一篇
Day-08 express API開發(下)
系列文
利用 node.js/express 架設網站26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言