Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Express.js Basics

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. This guide covers key concepts, basic examples, and best practices for getting started with Express.js.

Key Concepts of Express.js

  • Middleware: Functions that execute during the lifecycle of a request to the server.
  • Routing: Defining application endpoints (URIs) and how they respond to client requests.
  • Request and Response Objects: Objects representing the HTTP request and response, respectively.

Installing Express.js

To install Express.js, first create a new Node.js project and then use npm to install Express:

mkdir my-express-app
cd my-express-app
npm init -y
npm install express --save

Creating a Basic Express Server

Create a basic Express server that listens for incoming requests and sends a response:

Example: Basic Express Server

// app.js
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}/`);
});

To run the server, use the following command:

node app.js

Handling Different Routes

Use the app.get, app.post, app.put, and app.delete methods to handle different routes and HTTP methods:

Example: Handling Routes

// routes.js
const express = require('express');
const app = express();
const port = 3000;

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

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

app.post('/submit', (req, res) => {
    res.send('Form Submitted');
});

app.put('/update', (req, res) => {
    res.send('Data Updated');
});

app.delete('/delete', (req, res) => {
    res.send('Data Deleted');
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Using Middleware

Middleware functions are executed during the lifecycle of a request to the server. Use the app.use method to apply middleware:

Example: Using Middleware

// middleware.js
const express = require('express');
const app = express();
const port = 3000;

// Logger middleware
const logger = (req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
};

// Apply middleware
app.use(logger);

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

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Serving Static Files

Use the express.static middleware to serve static files, such as HTML, CSS, and JavaScript files:

Example: Serving Static Files

// static.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

// Serve static files
app.use(express.static(path.join(__dirname, 'public')));

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Create a public directory in your project and add static files (e.g., index.html, style.css) to it. Express will serve these files automatically.

Handling Form Data

Use the express.urlencoded middleware to parse URL-encoded form data:

Example: Handling Form Data

// form.js
const express = require('express');
const app = express();
const port = 3000;

// Parse URL-encoded form data
app.use(express.urlencoded({ extended: true }));

app.post('/submit', (req, res) => {
    res.send(`Form Submitted: ${req.body.name}`);
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Best Practices for Express.js Development

  • Use Middleware: Leverage middleware for common tasks such as logging, authentication, and error handling.
  • Modular Code: Organize your code into smaller, reusable modules to improve maintainability.
  • Security: Implement security best practices, such as validating user inputs and using HTTPS.
  • Error Handling: Implement robust error handling to manage runtime exceptions and send appropriate responses.
  • Environment Variables: Use environment variables to manage configuration settings.

Testing Express.js Applications

Test your Express.js applications using frameworks like Mocha, Chai, and Supertest:

Example: Testing with Mocha, Chai, and Supertest

// Install Mocha, Chai, and Supertest
// npm install --save-dev mocha chai supertest

// test/app.test.js
const chai = require('chai');
const expect = chai.expect;
const request = require('supertest');
const express = require('express');

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

describe('GET /', () => {
    it('should respond with "Hello, World!"', (done) => {
        request(app)
            .get('/')
            .expect('Content-Type', /text\/html/)
            .expect(200, 'Hello, World!', done);
    });
});

// Define test script in package.json
// "scripts": {
//   "test": "mocha"
// }

// Run tests with NPM
// npm run test

Key Points

  • Middleware: Functions that execute during the lifecycle of a request to the server.
  • Routing: Defining application endpoints (URIs) and how they respond to client requests.
  • Request and Response Objects: Objects representing the HTTP request and response, respectively.
  • Follow best practices for Express.js development, such as using middleware, organizing code into modules, implementing security best practices, handling errors properly, and using environment variables.

Conclusion

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. By understanding and implementing the key concepts, basic examples, and best practices covered in this guide, you can effectively use Express.js in your Node.js projects. Happy coding!