Handling UnknownAction in Middleware
Demonstrate how to create a middleware that listens for UnknownAction to perform logging or error reporting.
const express = require('express');
const app = express();
// Middleware function to handle unknown actions
const unknownActionHandler = (req, res, next) => {
// Log the unknown action or report an error
console.error(`Unknown action: ${req.method} ${req.originalUrl}`);
// Send response with 404 status
res.status(404).send('Action not found.');
};
// Apply the middleware
app.use(unknownActionHandler);
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
This example captures any requests that do not match defined routes (unknown actions) using an Express.js middleware. It logs the unknown action and sends a 404 response.
/* CSS for custom 404 page */
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: Arial, sans-serif;
}
.not-found {
text-align: center;
}
.not-found h1 {
font-size: 48px;
color: #333;
}
.not-found p {
color: #666;
}
This CSS provides styling for a custom 404 page. It centers text both horizontally and vertically and styles the heading and paragraph elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 Not Found</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="not-found">
<h1>404</h1>
<p>The action you requested could not be found.</p>
</div>
</body>
</html>
This HTML snippet creates a custom 404 page that displays a message indicating the requested action could not be found. It includes a link to the CSS file that contains the styling.