ocram
ocram

Reputation: 1444

Serve HTML with Express

I have an HTML file (privacy.html) and I want to serve it as home. I wrote the following:

app.get('/', (req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'})
  res.write(require('./privacy.html'))
  res.end()
})

What is wrong?

Upvotes: 12

Views: 38089

Answers (3)

matt
matt

Reputation: 1753

app.get('/', function(req, res){
  res.sendFile(__dirname + 'privacy.html');
});

Here is a good example: https://codeforgeek.com/render-html-file-expressjs/

Upvotes: 1

Aehmlo
Aehmlo

Reputation: 930

You don't use require to include html. Take a look at express's res.sendFile and express.static. It looks like you probably want the latter, but the former is the more flexible one if you're sure you want the structure you have.

Here's a little more information about require and the module system.

Edit: I urge you to read the links I provided, but I'll give you some code to use anyway so you don't end up using bad techniques.

The full implementation is super-simple:

// Somewhere above, probably where you `require()` express and friends.
const path = require('path')

// Later on. app could also be router, etc., if you ever get that far

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

// If you think it's still readable, you should be able rewrite this as follows.

app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'privacy.html')))

There are ways to make this fancier (bindings, etc.), but none of them are worth doing when this works fine as-is. This will work everywhere that express does, including on systems where the path delimiter/file system hierarchy is different.

Upvotes: 6

Tim
Tim

Reputation: 654

This may be what you are looking for:

app.get('/', function(req, res){
res.sendFile(__dirname + '/privacy.html');
});

Upvotes: 23

Related Questions