إعادة التوجيه
جزء من قسم أساسيات Express في رحلة Node.js على Coddy. الدرس 10 من 20.
تتغير الصفحات، وينبغي أن تظل الروابط القديمة في الإشارات المرجعية ونتائج البحث تؤدي إلى مكان ما.
app.get('/old-prices', (req, res) => {
res.redirect(301, '/prices');
});تجيب إعادة التوجيه برمز حالة وترويسة Location تحدد عنوان URL الجديد، ويطلب المتصفح ذلك العنوان فورًا. يضبط res.redirect كليهما.
يوضح رمز الحالة مدة استمرار الانتقال. يعني 301 أن الانتقال دائم: تتذكر المتصفحات ومحركات البحث العنوان الجديد وتتوقف عن طلب العنوان القديم. أما 302، وهو الرمز الافتراضي عند عدم تمرير أي رمز حالة، فيعني أن الانتقال مؤقت، ولذلك تواصل استخدام عنوان URL القديم.
التحدي
سهل- انتقل
GET /menuإلى/recipesنهائيًا. - انتقل
GET /menu/:idإلى/recipes/:id، مع المعرّف نفسه.
أرسل GET /menu/3 واقرأ الحالة وترويسة Location. أرسل GET /menu/42 أيضًا.
جرّب بنفسك
import express from 'express';
import { recipes } from './data.js';
const app = express();
app.use(express.static('public'));
const escapeHtml = (text) =>
text
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
app.get('/', (req, res) => {
const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
res.send(`<link rel="stylesheet" href="/style.css"><h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});
// ترسل type('text') نصًا عاديًا، لذا يظهر كل عنوان في سطر مستقل.
app.get('/recipes', (req, res) => {
const { tag } = req.query;
const list = tag ? recipes.filter((recipe) => recipe.tags.includes(tag)) : recipes;
res.type('text').send(list.map((recipe) => recipe.title).join('\n'));
});
app.get('/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).send('No such recipe');
return;
}
res.send(recipe.title);
});
app.get('/api/recipes', (req, res) => {
res.json(recipes);
});
app.get('/api/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
res.json(recipe);
});
app.get('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});