Building Web Applications with Express

Topic Outline (30-min)

  1. Introduction to Express:

    • Installing and Setting Up:

      • Install Express using npm:

        bash코드 복사npm install express
      • Create a new file named app.js and initialize Express:

        javascript코드 복사const express = require('express');
        const app = express();
    • Basic Structure of an Express App:

      javascript코드 복사app.get('/', (req, res) => {
          res.send('Welcome to Express!');
      });
      
      const PORT = 3000;
      app.listen(PORT, () => {
          console.log(`Server running on http://localhost:${PORT}`);
      });
  2. Routing in Express:

    • Defining GET, POST, PUT, DELETE Routes:

      javascript코드 복사app.get('/users', (req, res) => res.send('Retrieve all users'));
      app.post('/users', (req, res) => res.send('Create a new user'));
      app.put('/users/:id', (req, res) => res.send(`Update user with ID ${req.params.id}`));
      app.delete('/users/:id', (req, res) => res.send(`Delete user with ID ${req.params.id}`));
    • Route Parameters and Query Strings:

      javascript코드 복사app.get('/products/:id', (req, res) => {
          res.send(`Product ID: ${req.params.id}`);
      });
      
      app.get('/search', (req, res) => {
          const query = req.query.q;
          res.send(`Search query: ${query}`);
      });
  3. Middleware in Express:

    • Built-in Middleware:

      • Use middleware to parse JSON request bodies:

        javascript코드 복사app.use(express.json());
    • Custom Middleware:

      • Create a custom middleware to log requests:

        javascript코드 복사app.use((req, res, next) => {
            console.log(`${req.method} ${req.url}`);
            next();
        });

Last updated