Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
ocram Avatar asked Jun 20 '17 11:06

ocram


People also ask

Can I use Express for frontend?

Yes, it is possible, you can use Express to serve your static files (frontend ReactJS) and also your backend routes.

Can Express serve static files?

Express offers a built-in middleware to serve your static files and modularizes content within a client-side directory in one line of code.


2 Answers

This may be what you are looking for:

app.get('/', function(req, res){
res.sendFile(__dirname + '/privacy.html');
});
like image 130
Tim Avatar answered Oct 16 '22 19:10

Tim


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.

like image 6
Aehmlo Avatar answered Oct 16 '22 17:10

Aehmlo