Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Serving Static Files | Serving Static and Dynamic Content
Express.js Essentials for Backend Development

Serving Static Files

Sveip for å vise menyen

To efficiently deliver resources like images, stylesheets, and client-side scripts to users, you need to serve static files in your Express.js application. Static files are assets that do not change dynamically on the server, such as HTML, CSS, JavaScript, and image files. Express.js provides a built-in middleware called express.static() for this purpose. When you use this middleware, Express will automatically map requests to files in a specified directory, allowing users to access those resources directly via their URLs.

A common directory structure for serving static files looks like this:

project-root/
  public/
    index.html
    styles.css
    logo.png
  app.js

Following this structure, you place all your static assets in the public directory. This keeps your project organized and prevents accidental exposure of sensitive files. It is best practice to use a clearly named folder like public or static and avoid placing server-side code within this directory.

To enable static file serving, you add the express.static() middleware to your app configuration. Here is how you can set it up in your main application file.

const express = require('express');
const path = require('path');

const app = express();

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

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

In this example, express.static() is used to serve files from the public directory. The path.join(__dirname, 'public') ensures that the path is correctly resolved regardless of where the script is run. Once this middleware is added, any file within the public directory can be accessed via its relative URL. For instance, a request to http://localhost:3000/styles.css will serve the styles.css file located in the public folder. This approach simplifies asset management and improves performance by letting the framework handle static file delivery.

question mark

Which of the following is the correct way to serve static files from a directory named public in an Express.js app?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 5. Kapittel 1

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 5. Kapittel 1
some-alt