Welcome to the Node.js Express tutorial! Express.js is a popular web application framework for Node.js, known for its simplicity and flexibility. Let's dive into the essentials of creating a basic server and handling routes.

🧰 Prerequisites

  • Node.js installed on your machine
  • Basic understanding of JavaScript
  • A code editor (e.g., VS Code)

📌 Step-by-Step Guide

  1. Initialize a Project
    Open your terminal and run:

    npm init -y
    

    This creates a package.json file for your project.

  2. Install Express
    Use npm to install Express:

    npm install express
    

    📦 Express will now be available in your project directory.

  3. Create a Server
    Create a file app.js and add:

    const express = require('express');
    const app = express();
    const port = 3000;
    
    app.get('/', (req, res) => {
      res.send('Hello from Express!');
    });
    
    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}`);
    });
    

    🔄 Run the server with node app.js and visit http://localhost:3000 in your browser.

  4. Handle Routes
    Define routes for different endpoints:

    app.get('/about', (req, res) => {
      res.send('About page');
    });
    
    app.post('/submit', (req, res) => {
      res.send('Form submitted');
    });
    

    🌐 Explore route handling in-depth at /en/resources/tutorials/express-js.

🧠 Key Concepts

  • Routing: Map URLs to functions
  • Middleware: Process requests before reaching the route
  • Templates: Render dynamic HTML with engines like EJS

📌 Tips for Beginners

  • Use express-generator to scaffold projects:
    npx express-generator
    
  • Check the Express.js documentation for advanced features
  • Practice with real-world examples like APIs or blogs
express_js_logo

For more on Node.js fundamentals, visit /en/resources/tutorials/nodejs-basics. Happy coding! 🌟