Home  Nodejs   How to serv ...

How to serve static html files from express server

Serving static files from an Express server is straightforward. Express provides a built-in middleware function called express.static to serve static files such as HTML, CSS, JavaScript, images, etc. Here's how to set it up:

  1. Install Express: First, make sure you have Express installed in your project. If not, install it using npm:

    npm install express
    
  2. Create an Express server: Set up a basic Express server in a file, for example, src/index.ts.

  3. Serve static files: Use the express.static middleware to serve static files from a directory.

Here is a complete example:

Directory Structure

my-express-app/
├── public/
│   ├── images/
│   │   └── logo.png
│   ├── js/
│   │   └── script.js
│   └── css/
│       └── style.css
├── src/
│   └── index.ts
├── package.json
├── tsconfig.json
└── ...

Code Example

// src/index.ts
import express from 'express';
import path from 'path';

const app = express();
const port = 3000;

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

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

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

Steps

  1. Create Static Files: Place your static files (HTML, CSS, JavaScript, images, etc.) in the public directory.

  2. Update package.json: Ensure your package.json has the necessary scripts and dependencies.

    {
      "name": "my-express-app",
      "version": "1.0.0",
      "main": "dist/index.js",
      "scripts": {
        "build": "tsc",
        "start": "node dist/index.js",
        "dev": "ts-node-dev --respawn --transpile-only src/index.ts"
      },
      "dependencies": {
        "express": "^4.17.1"
      },
      "devDependencies": {
        "ts-node-dev": "^1.1.8",
        "typescript": "^4.3.5",
        "@types/express": "^4.17.13",
        "@types/node": "^14.14.41"
      }
    }
    
  3. Compile TypeScript: Compile your TypeScript code to JavaScript.

    npx tsc
    
  4. Run the Server: Start your Express server.

    npm start
    
  5. Access Static Files: Open your browser and navigate to http://localhost:3000/. You should see your index.html file served, and you can access other static files such as CSS, JavaScript, and images.

Published on: Jun 26, 2024, 05:51 AM  
 

Comments

Add your comment