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?
Yes, it is possible, you can use Express to serve your static files (frontend ReactJS) and also your backend routes.
Express offers a built-in middleware to serve your static files and modularizes content within a client-side directory in one line of code.
This may be what you are looking for:
app.get('/', function(req, res){
res.sendFile(__dirname + '/privacy.html');
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With