How to Fix 'Cannot GET /route' Error in Express
Cannot GET /route error in Express happens when the requested route is not defined or middleware order is wrong. To fix it, ensure you have a matching app.get() or other HTTP method route handler for the path, and that it is registered before any catch-all middleware.Why This Happens
This error occurs because Express does not find a route handler matching the requested URL and HTTP method. It usually means you forgot to define the route, misspelled the path, or placed the route handler after middleware that ends the request.
import express from 'express'; const app = express(); // Missing route for '/hello' app.listen(3000, () => { console.log('Server running on port 3000'); });
The Fix
Define the route handler for the requested path using app.get() or the appropriate HTTP method. Also, make sure this route is registered before any middleware that sends a response or handles 404 errors.
import express from 'express'; const app = express(); app.get('/hello', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
Prevention
Always define routes explicitly for each path and HTTP method you want to support. Use consistent naming and check for typos. Register routes before any catch-all middleware like 404 handlers. Use tools like linters or TypeScript to catch missing routes early.
Related Errors
404 Not Found: Happens when no route matches the request.
Method Not Allowed: Occurs if the route exists but the HTTP method (GET, POST, etc.) is not handled.
Quick fixes include adding the missing route or supporting the correct HTTP method.