Çerezlerle Hatırlama
Coddy'nin Node.js Journey'sinin Kimlik Doğrulama ve Güvenlik bölümünün bir parçası. Ders 4 / 17.
HTTP, istekler arasında sizi hatırlamaz: her istek tek başına gelir ve sunucu bunun aynı tarayıcıdan geldiğini anlayamaz. Çerez bunu çözer. Sunucu bir Set-Cookie başlığıyla yanıt verir ve tarayıcı, bu siteye daha sonra gönderdiği her istekte değeri bir Cookie başlığıyla geri gönderir.
res.cookie(name, value) bir çerez ayarlar. Express, Cookie başlığını sizin için okumaz (bunu cookie-parser paketi yapar); bu yüzden cookies.js size parseCookies işlevini sağlar. Her değer metin olarak gelir.
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}`);
});Görev
KolayGET /visit,visitsçerezini okur, 1 ekler, çerezi yeni sayıya ayarlar ve{ "visits": n }yanıtını verir.- Çerezi olmayan bir tarayıcı
1alır.
GET /visit isteğini üç kez gönderin, ardından Set-Cookie değerini görmek için Headers bölümünü açın.
Kendin dene
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 });
});
// Bu tarayıcının GET /visit isteğini kaç kez yaptığını sayar.
app.get('/visit', (req, res) => {
const visits = 1;
res.json({ visits });
});
// Notlar. Şimdilik herkes bunları okuyabilir ve yazabilir.
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');
});
Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.
Kimlik Doğrulama ve Güvenlik bölümündeki tüm dersler
2Oturumlar ve Çerezler
Çerezlerle HatırlamaGiriş Oturumları