DEV Community

Rigal Patel
Rigal Patel

Posted on

Top Express.js Mistakes and How to Fix Them

Express.js is a popular framework for building web applications in Node.js, but even seasoned developers encounter errors that can be tricky to debug. This guide will cover some of the most common Express.js errors, explain why they occur, and provide practical fixes to get your application back on track.

1. Error: Cannot Set Headers After They Are Sent

This error usually occurs when you attempt to send multiple responses for the same request. For example, you might accidentally call res.send() or res.json() more than once in a route handler.

Example:

app.get('/example', (req, res) => {
    res.send('First response');
    res.send('Second response'); // This will throw the error.
});

Enter fullscreen mode Exit fullscreen mode

Fix:
Ensure you only send one response per request. Use conditional logic or return statements to prevent further execution after sending a response.

app.get('/example', (req, res) => {
    if (!req.query.param) {
        return res.status(400).send('Bad Request');
    }
    res.send('Valid Request');
});

Enter fullscreen mode Exit fullscreen mode

2. Error: Middleware Not Executing

This happens when middleware is not properly linked or next() is not called within it. Middleware functions must explicitly pass control to the next middleware or route handler.

Example:

app.use((req, res) => {
    console.log('Middleware executed');
    // Forgot to call next()
});
app.get('/test', (req, res) => {
    res.send('Hello, World!');
});

Enter fullscreen mode Exit fullscreen mode

Fix:
Call next() unless the middleware ends the response.

app.use((req, res, next) => {
    console.log('Middleware executed');
    next(); // Pass control to the next middleware or route
});

Enter fullscreen mode Exit fullscreen mode

3. Error: req.body Undefined

If req.body is undefined, it's likely because you forgot to use a body-parsing middleware, such as express.json() or express.urlencoded().

Example:

app.post('/submit', (req, res) => {
    console.log(req.body); // undefined
});
Enter fullscreen mode Exit fullscreen mode

Fix:

Include the body-parsing middleware in your app initialization.

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post('/submit', (req, res) => {
    console.log(req.body); // Now it works
    res.send('Data received');
});
Enter fullscreen mode Exit fullscreen mode

4. Error: Route Not Found (404)

This error occurs when no route matches the incoming request. By default, Express doesn’t provide a 404 handler.

Fix:

Add a catch-all middleware at the end of your route definitions to handle 404 errors.

app.use((req, res) => {
    res.status(404).send('Page Not Found');
});

Enter fullscreen mode Exit fullscreen mode

5. Error: EADDRINUSE (Port in Use)

This happens when another process is already using the port your app is trying to bind to.

Error: listen EADDRINUSE: address already in use :::3000
Enter fullscreen mode Exit fullscreen mode

Fix:
Find and terminate the conflicting process or use a different port. You can also handle the error programmatically:

const port = process.env.PORT || 3000;

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
}).on('error', (err) => {
    if (err.code === 'EADDRINUSE') {
        console.error(`Port ${port} is already in use. Please use a different port.`);
    }
});

Enter fullscreen mode Exit fullscreen mode

Express.js errors can be frustrating, but understanding their root causes makes them easier to solve. With these common fixes, you’ll be better equipped to debug your applications and keep your projects running smoothly.

If you found this guide helpful, hit the ❤️ icon and follow me for more JavaScript tips and tricks!

Top comments (0)