Menu
CoddyTech

쿠키로 기억하기

Coddy Node.js 여정의 인증과 보안 섹션에 포함된 레슨. 17개 중 4번째.

HTTP는 요청 사이에 사용자를 기억하지 않습니다. 각 요청은 따로 도착하며, 서버는 같은 브라우저에서 왔는지 알 수 없습니다. 쿠키가 이를 해결합니다. 서버는 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은 visits 쿠키를 읽고, 1을 더한 다음 쿠키를 새 횟수로 설정하고 { "visits": n }으로 응답합니다.
  • 쿠키가 없는 브라우저는 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실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

인증과 보안의 모든 레슨