🌐 Detecting your location…

كيفية إصلاح خطأ “لا يمكن الحصول على خطأ” في Express.js: دليل الحل الكامل

⏱️3 min read  ·  529 words

الخطألا يمكن الحصول على / (أو لا يمكن الحصول على /some-path) في المتصفح عند الضغط على خادم Express الخاص بك يعني أن Express قد تلقى الطلب ولكن ليس لديه معالج توجيه لهذا المسار والطريقة. إليك كيفية إصلاح كل الأسباب.

ماذا يعني هذا الخطأ

“لا يمكن الحصول على /المسار” هو استجابة Express الافتراضية 404 – فقد تلقى طلب GET لـ /المسار ولكنه لم يعثر على مسار مطابق. وصل الطلب إلى الخادم الخاص بك (جيد)، ولكن لا يوجد مسار يتعامل معه. الإصلاح هو تحديد المسار الصحيح أو تقديم الملفات الصحيحة.

السبب الأول: لم يتم تحديد مسار للمسار

// 🐛 Server has no route for the root path
const express = require('express');
const app = express();
app.listen(3000);
// Visiting http://localhost:3000/ → "Cannot GET /"

// ✅ Define a route for /
app.get('/', (req, res) => {
  res.send('Hello World');
});
app.listen(3000);

السبب 2: أسلوب HTTP خاطئ

// 🐛 Route is POST but you're making a GET request
app.post('/users', createUser);
// Browsing to /users (a GET) → "Cannot GET /users"
// (the POST route exists, but not a GET route)

// ✅ Add a GET route if you need one
app.get('/users', getUsers);    // for GET requests
app.post('/users', createUser); // for POST requests

السبب 3: تقديم الملفات الثابتة بشكل غير صحيح

// 🐛 Expecting index.html to serve but static middleware isn't set up
// Visiting / → "Cannot GET /" because there's no route or static config

// ✅ Serve static files (HTML, CSS, JS) from a directory
app.use(express.static('public'));
// Now files in ./public are served: /index.html at /, /style.css, etc.

// ✅ Or serve a specific file at the root
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

السبب 4: تحديد المسار بعد app.listen أو ترتيب البرامج الوسيطة

// 🐛 Routes defined AFTER listen() never register
app.listen(3000);
app.get('/', handler);   // ❌ too late - server already started

// ✅ Define routes BEFORE listen()
app.get('/', handler);
app.listen(3000);

// 🐛 A catch-all or 404 middleware BEFORE your routes intercepts everything
app.use((req, res) => res.status(404).send('Not found'));
app.get('/users', getUsers);   // ❌ never reached - 404 middleware ran first

// ✅ Put the 404 handler LAST
app.get('/users', getUsers);
app.use((req, res) => res.status(404).send('Not found'));   // last

السبب 5: شرطة مائلة زائدة أو عدم تطابق المسار

// 🐛 Route path doesn't exactly match the request
app.get('/users', getUsers);
// Request to /users/ (trailing slash) may not match depending on config

// ✅ Express matches /users and /users/ by default in most versions,
// but be consistent. For explicit control:
app.get('/users', getUsers);
// Or handle both:
app.get(['/users', '/users/'], getUsers);

السبب 6: جهاز التوجيه غير مثبت بشكل صحيح

// 🐛 Router defined but not mounted, or wrong prefix
const router = express.Router();
router.get('/list', getList);
// Forgot to mount it, or mounted at wrong path

// ✅ Mount the router with a base path
const usersRouter = express.Router();
usersRouter.get('/list', getList);
app.use('/users', usersRouter);
// Now the route is at /users/list, not /list

تصحيح الأخطاء: راجع مساراتك المسجلة

// List all registered routes to verify what exists
app._router.stack
  .filter(layer => layer.route)
  .forEach(layer => {
    const methods = Object.keys(layer.route.methods).join(', ').toUpperCase();
    console.log(`${methods} ${layer.route.path}`);
  });
// Prints: GET /, POST /users, etc.
// Confirms whether the route you expect actually exists

التعامل السليم 404

// Define all your routes first
app.get('/', homeHandler);
app.get('/users', getUsers);
app.post('/users', createUser);

// Then a catch-all 404 handler LAST (nicer than default "Cannot GET")
app.use((req, res) => {
  res.status(404).json({ error: `Route not found: ${req.method} ${req.path}` });
});

الأسئلة المتداولة

س: لماذا تظهر لي رسالة “لا يمكن الحصول على /” على المسار الجذر؟
ج: لم تقم بتحديد مسار لـ/. أضفapp.get('/', (req, res) => res.send('Hello')) أو تقديم ملفات ثابتة معapp.use(express.static('public')) لذلك يتم تحميل ملف Index.html من الجذر.

س: يعمل مسار POST الخاص بي ولكن GET يعطي لا يمكن GET. لماذا؟
ج: لقد حددت المسار بـapp.post() ولكنهم يقدمون طلب GET (على سبيل المثال، كتابة عنوان URL في المتصفح الذي يرسل GET). أضفapp.get() المسار لهذا المسار إذا كنت بحاجة إلى التعامل مع طلبات GET أيضًا.

س: كيف أقوم بخدمة صفحة HTML في الجذر؟
ج: استخدمapp.use(express.static('public')) لخدمة دليل (يتم تحميل ملف Index.html على /)، أوapp.get('/', (req, res) => res.sendFile(__dirname + '/index.html')) لملف معين.

س: لماذا لا يمكن الحصول على مسارات جهاز التوجيه الخاص بي؟
ج: ربما لم تقم بتثبيت جهاز التوجيه (app.use('/prefix', router))، أو أن المسار الكامل مختلف عن المتوقع. جهاز توجيه مثبت على/users مع الطريق/list يتم الوصول إليه في/users/list، وليس/list. تحقق من المسار المدمج.

س: هل ترتيب المسار مهم في Express؟
ج: نعم — يطابق Express المسارات من أعلى إلى أسفل. يجب أن تأتي البرامج الوسيطة لاستقبال الرسائل الخاطئة أو 404 أخيرًا، بعد كل المسارات المحددة، وإلا فإنها تعترض الطلبات قبل أن تصل إلى مساراتك. ترتيب مساراتك من الخاص إلى العام.

الخلاصة

“لا يمكن الحصول على /” يعني أن Express قد تلقى الطلب ولكن ليس لديه مسار مطابق لذلك المسار والأسلوب. الإصلاحات:تحديد مسار للمسار (app.get('/', ...))، ومطابقة طريقة HTTP الصحيحة، وخدمة الملفات الثابتة معexpress.static()، حدد المسارات قبلapp.listen()، ووضع معالجات 404 أخيرًا. إذا كان جهاز توجيه، فتأكد من تثبيته بالبادئة الصحيحة. عندما تتعثر، قم بتسجيل مساراتك المسجلة لتأكيد ما هو موجود بالفعل. بمجرد التحقق من تحديد المسار وتثبيته بشكل صحيح وتطابق طريقة الطلب ومساره، يتم حل الخطأ.

MD Rafikul Islam

Written by

MD Rafikul Islam is a software developer and the editor of TechPulse. He writes about developer tooling, hardware, and the practical decisions that come up in day-to-day engineering work — which laptop to buy, which framework to commit to, why a build broke at 2am. He tests the tools he writes about and says plainly when something is not worth the money. Corrections and corrections requests are welcome at rony.yf25@gmail.com.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇬🇧 English🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা