Hello World: Create a basic Express application that outputs "Hello World" when you visit the root URL.
Routing: Create multiple routes that return different messages when visited. For example, a route for "/about" that returns "About Us" and a route for "/contact" that returns "Contact Us".
Dynamic Routes: Create a route that takes a parameter, such as "/hello/:name", that outputs a personalized message, such as "Hello, [name]".
Templates: Use a templating engine, such as EJS or Handlebars, to render a dynamic HTML page. For example, create a route that displays a list of items stored in an array.
Forms: Create a form that allows users to submit data to the server. Use a POST route to receive the form data and display it on the page.
Middleware: Create a custom middleware function that logs the current time and URL of each request. Use this middleware in your application to see it in action.
REST API: Create a REST API that allows clients to retrieve and manipulate data stored in a database. Use the CRUD (Create, Read, Update, Delete) operations to perform these actions.
These exercises should help you get started with Express and learn the basics of building web applications with Node.js and Express. As you progress, you can add more complexity and features to your applications to continue building your skills.
Hello World:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Routing:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Home');
});
app.get('/about', (req, res) => {
res.send('About Us');
});
app.get('/contact', (req, res) => {
res.send('Contact Us');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Dynamic Routes:
const express = require('express');
const app = express();
app.get('/hello/:name', (req, res) => {
const name = req.params.name;
res.send(`Hello, ${name}`);
});
app.listen(3000, () => {
console.log('App listening on port 3000!');
});
Templates:
const express = require('express');
const app = express();
const ejs = require('ejs');
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', { items: ['Item 1', 'Item 2', 'Item 3'] });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Forms:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.send(`
<form action="/" method="post">
<input type="text" name="message">
<button type="submit">Submit</button>
</form>
`);
});
app.post('/', (req, res) => {
res.send(`You submitted: ${req.body.message}`);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Middleware:
const express = require('express');
const app = express();
const logMiddleware = (req, res, next) => {
console.log(`${new Date().toString()}: ${req.method} ${req.url}`);
next();
};
app.use(logMiddleware);
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
REST API:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const tasks = [
{ id: 1, description: 'Task 1' },
{ id: 2, description: 'Task 2' },
{ id: 3, description: 'Task 3' }
];
app.get('/tasks', (req, res) => {
res.json(tasks);
});
app.get('/tasks/:id', (req, res) => {
const task = tasks.find(task => task.id === parseInt(req.params.id));
if (!task) {
return res.status(404).json({ message: 'Task not found' });
}
res.json(task);
});
app.post('/tasks', (req, res) => {
const task = { id: tasks.length + 1, description: req.body.description };
tasks.push(task);
res.json(task);
});
app.put('/tasks/:id', (req, res) => {
const task = tasks.find(task => task.id === parseInt(req.params.id));
if (!task) {
return res.status(404).json({ message: 'Task not found' });
}
task.description = req.body.description;
res.json(task);
});
app.delete('/tasks/:id', (req, res) => {
const taskIndex = tasks.findIndex(task => task.id === parseInt(req.params.id));
if (taskIndex === -1) {
return res.status(404).json({ message: 'Task not found' });
}
tasks.splice(taskIndex, 1);
res.json({ message: 'Task deleted' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
This code creates a REST API for a simple task management system, where tasks can be retrieved, created, updated, and deleted. The API uses the HTTP methods GET, POST, PUT, and DELETE to perform these actions, respectively.
This is a simple example to get you started with building a REST API using Express. As you progress, you can add more complexity, error handling, and validation to your API to make it more robust.