javascripthtmlexpressserving

Express Serving a Static File: Server and Client in Different Locations


I'm trying to get my express to serve up static files that are in another location:

This is the current directory I have:

|__client
|   |__thumbnails.html
|
|__server
    |__app.js

I tried to just use app.use(express.static(path.join(__dirname, '..', 'client')));, but it wouldn't serve the file at all. However, when I used the same path.join for a get request on '/' it will send the file.

Here it the code I have at the moment. It's working, thank God, but I want to see if there is a way for me to serve it without actually sending the file.

const express = require('express');
const path = require('path');
const similar = require('./routes/similar');
const image = require('./routes/images');

const app = express();

app.use(express.static(path.join(__dirname, '..', 'client')));

app.use('/item', similar);
app.use('/thumbnail', image);

app.get('/', (req, res) => res.status(200).sendFile(path.join(__dirname, '..', 'client', 'thumbnail.html')));

module.exports = app;

Solution

  • You can make the file anything you want, through configuration of the serve-static module: https://expressjs.com/en/resources/middleware/serve-static.html

    From that page:

    var express = require('express')
    var serveStatic = require('serve-static')
    
    var app = express()
    
    app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']}))
    app.listen(3000)
    

    now anything that you put in the 'index' array will be looked at, in the order you defined. Otherwise, you would still be able to get to your html file if you put the actual filename in the url.