Express.js v5

MD
R
Markdown

Express.js 5 modernizes the framework with automatic async error handling, cleaner method signatures, and stricter API conventions. Key improvements include simplified error handling, removal of deprecated features, and better async support for template rendering. These changes make Express more maintainable and aligned with modern JavaScript practices, with automatic async error handling being the most significant improvement. Note: Express.js uses Node.js's built-in HTTP server capabilities but provides a framework layer for building web applications more easily

Here are the key changes in Express.js v5:

  1. Automatic async error handling No need for explicit try/catch blocks Errors automatically forwarded to error middleware

  2. Updated method signatures Deprecated: res.json(obj, status) New: res.status(200).json({}) res.send(status) replaced with res.sendStatus()

  3. Pluralized request methods acceptsCharset → acceptsCharsets acceptsEncoding → acceptsEncodings acceptsLanguage → acceptsLanguages

  4. Removed deprecated features req.param() removed res.sendfile renamed to res.sendFile()

  5. Route matching changes New wildcard syntax: /path/*splat RegExp route patterns removed Multiple explicit routes needed instead

  6. Enforced async template rendering res.render() is now strictly asynchronous

===================================================== ================= Async Error Handling ==================== // V4 app.get('/user/:id', async (req, res, next) => { try { const user = await User.findById(req.params.id); res.json(user); } catch (err) { next(err); } });

// V5 - Simpler app.get('/user/:id', async (req, res) => { const user = await User.findById(req.params.id); res.json(user); });

================= Method Signatures ==================== // V4 res.json({ message: 'OK' }, 200); res.send(200);

// V5 res.status(200).json({ message: 'OK' }); res.sendStatus(200);

================= Parameter Access ==================== // V4 const id = req.param('id');

// V5 const id = req.params.id; const queryId = req.query.id; const bodyId = req.body.id;

================= Route Patterns ==================== // V4 app.get('/(page|discussion)/:slug', handler);

// V5 app.get(['/page/:slug', '/discussion/:slug'], handler);

================= Wildcard Routes ==================== // V4 app.get('/path/*', handler);

// V5 app.get('/path/*splat', handler);

Created on 10/30/2024