11

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?

ocram
  • 1,384
  • 6
  • 20
  • 36

3 Answers3

23

This may be what you are looking for:

app.get('/', function(req, res){
res.sendFile(__dirname + '/privacy.html');
});
Tim
  • 623
  • 5
  • 12
6

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.

Aehmlo
  • 930
  • 1
  • 8
  • 20
  • Itried with `res.write(express.static('./privacy.html'))` bot it doesn't seem to work... – ocram Jun 20 '17 at 11:18
  • yeah but I don't have a directory, it's just a file and I don't wanna create a new directory for one file. I also tried `res.sendFile(path.join(__dirname, 'privacy.html'))` – ocram Jun 20 '17 at 11:22
0
app.get('/', function(req, res){
  res.sendFile(__dirname + 'privacy.html');
});

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

matt
  • 1,680
  • 1
  • 13
  • 16