0
0
Expressframework~5 mins

Express application structure

Choose your learning style9 modes available
Introduction

Express application structure helps organize your code so it is easy to read and maintain. It keeps your server setup, routes, and logic in clear places.

When building a web server that handles different web pages or API endpoints.
When you want to separate your route handling from your main server setup.
When your project grows and you need to keep files organized for teamwork.
When you want to add middleware like logging or authentication in a clean way.
Syntax
Express
const express = require('express');
const app = express();

// Middleware setup
app.use(express.json());

// Routes
app.get('/', (req, res) => {
  res.send('Hello World');
});

// Start server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});

The app object is your main Express application.

Routes define how your app responds to different URLs and HTTP methods.

Examples
Basic Express app with one route and server listening on port 3000.
Express
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Home page');
});

app.listen(3000);
Express app that parses JSON body and echoes it back on POST /data.
Express
const express = require('express');
const app = express();

// Middleware example
app.use(express.json());

app.post('/data', (req, res) => {
  res.json(req.body);
});

app.listen(3000);
Shows how to organize routes in a separate file and use them in the main app.
Express
// Separate routes in another file (routes.js)
const express = require('express');
const router = express.Router();

router.get('/about', (req, res) => {
  res.send('About page');
});

module.exports = router;

// In main app file
const express = require('express');
const app = express();
const routes = require('./routes');

app.use('/', routes);

app.listen(3000);
Sample Program

This Express app has middleware that logs every request. It has two routes: '/' and '/about'. The server listens on port 3000.

Express
const express = require('express');
const app = express();

// Middleware to log request method and URL
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// Home route
app.get('/', (req, res) => {
  res.send('Welcome to the Home Page');
});

// About route
app.get('/about', (req, res) => {
  res.send('About Us');
});

// Start server
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});
OutputSuccess
Important Notes

Use app.use() to add middleware that runs for all routes.

Separate routes into different files as your app grows to keep code clean.

Always call next() in middleware to continue processing requests.

Summary

Express app structure organizes your server, routes, and middleware clearly.

Use app to set up routes and middleware.

Separate routes and middleware into files for better maintenance.