express.static not kicking in on file requests

Discussão em 'Angular' iniciado por Benjamin, Março 25, 2025.

  1. Benjamin

    Benjamin Guest

    So I have an express server set up to serve static content with express.static, some api routes and a last "failsafe" app.use('*'...) to serve the angular index.

    My issue is any /file.ext requests gets redirected to /file.ext/ and then goes to the failsafe. I've tried serving the files by having a check if they exist and serving them with sendFile instead of the index. But isn't that the whole point of express.static ?

    structure

    dist
    |-frontend //static
    |-|-3rdpartylicenses.txt
    |-|-browser
    |-|-|-index.html
    |-|-|-polyfills.js
    |-|-|-main.js
    |-|-|-styles.css
    |-|-|-favicon.ico
    |-other folders //middleware,models,routes
    |-index.js


    index.ts

    import express, { Application } from 'express';
    import mongoose from 'mongoose';
    import cors from 'cors';
    import dotenv from 'dotenv';
    import path from 'path';

    import apiRoutes from './routes/api';

    const app: Application = express();

    app.use(cors());
    dotenv.config();

    (async () => {
    const port: string | number = process.env.PORT || 3000;
    const un = process.env.MONGO_UN;
    const pw = process.env.MONGO_PW;
    const dbhost = process.env.DB_HOST;
    const protocol = process.env.DB_PROTOCOL;
    const db = process.env.DB_NAME;

    try {
    mongoose.connect(
    `${protocol}://${un}:${pw}@${dbhost}/?retryWrites=true&w=majority`,
    {
    dbName: db,
    }
    );
    console.log('[mongodb] Connected to DB');

    app.use(express.json());
    app.use(express.static(path.join(__dirname, 'frontend/browser')));

    app.use('/api', apiRoutes);

    app.use('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'frontend/browser/index.html'));
    });

    app.listen(port, () => {
    console.log('[server] Server running');
    });
    } catch (err) {
    console.log(`[server] Error: ${err}`);
    process.exit(1);
    }
    })();

    Continue reading...

Compartilhe esta Página