[Fixed] nodejs send html file to client


I use this function to send html file to client, but in client I get nothing (blank page) without error. Something I 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){
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>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <style something here </style>
      <script src="..."></script>
    <div> Somthing here </div>

    <script type="text/javascript">
        //something here


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.

Leave a Reply

(*) Required, Your email will not be published