Introduction to Generator-Express
Generator-Express is a powerful tool that allows developers to create robust web applications with Express.js effortlessly. It scaffolds a new Express application with a well-organized structure, enabling developers to focus on writing their business logic. In this guide, we’ll explore the various APIs provided by Generator-Express with practical code snippets and examples.
Creating a New Express Application
To start a new project, simply run:
yo express
This command will scaffold a new Express application with standard structure.
Setting Up Middleware
Middleware functions are essential in Express to handle requests. Here’s an example of setting up middleware:
const express = require('express'); const app = express();
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Creating Routes
Define routes to handle various endpoints efficiently:
const express = require('express'); const router = express.Router();
router.get('/', (req, res) => {
res.send('Home Page');
});
router.get('/about', (req, res) => {
res.send('About Page');
});
module.exports = router;
Handling Errors
Gracefully handle errors in your application:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Application Example
Let’s combine all these APIs into a simple web application:
const express = require('express'); const app = express(); const router = require('./router'); // Assuming the routes are in a separate file named router.js
app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use('/', router);
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
With this setup, you can extend your application with more routes, middleware, and error handlers as needed.
Hash: 73c943db51e67c72e6a6492f1550d15efbdccce046f5553d362c2ee917ca847c