التذكّر باستخدام ملفات تعريف الارتباط
جزء من قسم المصادقة والأمان في رحلة Node.js على Coddy. الدرس 4 من 17.
ينسى 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}`);
});التحدي
سهل- يقرأ
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');
});
يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.
جميع دروس المصادقة والأمان
2الجلسات وملفات تعريف الارتباط
التذكّر باستخدام ملفات تعريف الارتباطجلسات تسجيل الدخول