node.jsexpresshtml-rendering

nodejs send html file to client


I use this function to send a html file to the client, but in the client, I get nothing (blank page) without error. Is something wrong? please help.

    var express = require('express'); 
    var fs = require('fs');
    var app = express();
    app.set('view engine', 'jade');
    app.engine('jade', require('jade').__express); 
    app.get('/test', function(req, res) {
      fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
        res.send(text);
    });
    var port = process.env.PORT || 80;
    var server = app.listen(port);
    console.log('Express app started on port ' + port);

My test.html file

<!DOCTYPE html>
    <html>
       <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <style something here </style>
          <title>Test</title>
          <script src="..."></script>
       </head>
    <body>
        <div> Somthing here </div>
    
        <script type="text/javascript">
            //something here
        </script>
    </body>
</html>

Solution

  • Try your code like this:

    var app = express();
    app.get('/test', function(req, res) {
        res.sendFile('views/test.html', {root: __dirname })
    });
    
    1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

    2. You don't need the app.engine line, as that is handled internally by express.