JOHN SWANA
JOHN SWANA

Reputation: 3

How do i force express to serve static html documents having no file extentions with 'text/html' content type

I made a statically generated site with html files encoded as 'utf-8'

Served from express they reside in a static directory

I discovered after omitting the file extension of my webpages before saving them

when opened in the browser the webpages were getting downloaded instead of getting rendered as html documents normally would

til now couldn't find any relevant information on the subject.

Upvotes: 0

Views: 176

Answers (2)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

A very hacky way to do it will be setting the headers in the static options. Now you can add if clauses that say if the path doesn't have extension etc etc. But basically this will work:

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

app.use(express.static(<your directory>, {
  setHeaders: function (res, path, stat) {
    res.set('Content-Type', 'text/html');
  }
}))

app.listen(8080);

Upvotes: 0

Quentin
Quentin

Reputation: 943510

The static module accepts a setHeaders function which can dynamically add headers to any static file it serves.

You can test if the file hasn't got a file extension and add the header dynamically:

const express = require('express')
const app = express()
const port = 3000

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

// This is a bit quick and dirty, but should be suitable for most cases
const noFileExtension = /[^.]{5}$/;

const staticOptions = {
    setHeaders: (res, path, stat) => { 
        if (path.match(noFileExtension)) {
            res.set('Content-Type', "text/html");
        }
    }
}
app.use(express.static('public', staticOptions));

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Upvotes: 1

Related Questions