Menu
CoddyTech

זכירה באמצעות עוגיות

חלק מהיחידה אימות ואבטחה במסלול ה-Node.js של Coddy. שיעור 4 מתוך 17.

HTTP שוכח אותך בין בקשות: כל בקשה מגיעה לבדה, והשרת לא יכול לדעת שהיא הגיעה מאותו דפדפן. קובץ cookie פותר את הבעיה. השרת משיב עם כותרת Set-Cookie, והדפדפן שולח את הערך בחזרה בכותרת Cookie בכל בקשה מאוחרת יותר לאותו אתר.

res.cookie(name, value) מגדירה אחד. Express לא קוראת עבורך את הכותרת Cookie (החבילה cookie-parser הייתה עושה זאת), ולכן cookies.js מספקת לך את parseCookies. כל ערך מגיע כטקסט.

app.get('/theme/:name', (req, res) => {
    res.cookie('theme', req.params.name);
    res.send('Saved');
});

app.get('/', (req, res) => {
    const { theme = 'light' } = parseCookies(req.get('cookie'));
    res.send(`Your theme is ${theme}`);
});
challenge icon

אתגר

קל
  • GET /visit קורא את קובץ ה־cookie בשם visits, מוסיף 1, מגדיר את קובץ ה־cookie לערך החדש ומשיב { "visits": n }.
  • דפדפן ללא קובץ cookie מקבל 1.

שלחו GET /visit שלוש פעמים, ואז פתחו את כותרות כדי לראות את Set-Cookie.

נסו בעצמכם

import express from 'express';
import { parseCookies } from './cookies.js';
import { notes, users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';

const app = express();
app.use(express.json());

app.post('/signup', async (req, res) => {
    const username = String(req.body.username ?? '').trim().toLowerCase();
    const password = String(req.body.password ?? '');
    if (!username || password.length < 8) {
        return res.status(400).json({ error: 'Pick a username and a password of at least 8 characters' });
    }
    if (await users.findOne({ username })) {
        return res.status(409).json({ error: 'That username is taken' });
    }
    await users.insertOne({ username, passwordHash: await hashPassword(password) });
    res.status(201).json({ username });
});

app.post('/login', async (req, res) => {
    const username = String(req.body.username ?? '').trim().toLowerCase();
    const user = await users.findOne({ username });
    if (!user || !(await verifyPassword(String(req.body.password ?? ''), user.passwordHash))) {
        return res.status(401).json({ error: 'Wrong username or password' });
    }
    res.json({ username: user.username });
});

// סופר כמה פעמים הדפדפן הזה שלח בקשת GET ל-/visit.
app.get('/visit', (req, res) => {
    const visits = 1;
    res.json({ visits });
});

// פתקים. כרגע כל אחד יכול לקרוא ולכתוב אותם.
app.get('/notes', async (req, res) => {
    res.json(await notes.find().toArray());
});

app.post('/notes', async (req, res) => {
    const note = { text: String(req.body.text ?? '') };
    await notes.insertOne(note);
    res.status(201).json(note);
});

app.listen(3000, () => {
    console.log('Vault is running on port 3000');
});
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה אימות ואבטחה