Express Documentation
Learn how to use Express in your BackendGlitch project.
Installing Express
To add Express to your project, run the following command in your project directory:
npm install expressBasic Express Server
Here s a basic Express server setup:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});Routing in Express
Express makes it easy to define routes for your API:
app.get('/api/users', (req, res) => {
// Handle GET request to /api/users
});
app.post('/api/users', (req, res) => {
// Handle POST request to /api/users
});
app.put('/api/users/:id', (req, res) => {
// Handle PUT request to /api/users/:id
});
app.delete('/api/users/:id', (req, res) => {
// Handle DELETE request to /api/users/:id
});Middleware in Express
Middleware functions have access to the request and response objects. Here s an example:
const myMiddleware = (req, res, next) => {
console.log('This middleware runs for every request');
next();
};
app.use(myMiddleware);
// Or for a specific route
app.use('/api', myMiddleware);