54

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>
2
  • is that all your code?
    – mihai
    Dec 3, 2013 at 8:21
  • @mihai I have just edited Dec 3, 2013 at 8:27

7 Answers 7

118

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.

2
  • Why is that second parameter {root: __dirname } needed ?
    – sander
    Jul 31, 2021 at 14:00
  • it works to serve index.html this way, but if this file depends on assets, which are located nearby, I get errors. GET http://localhost:3000/vendor/polyfill.js net::ERR_ABORTED 404 (Not Found). how to resolve that? Aug 3, 2021 at 15:42
6

you can render the page in express more easily


 var app   = require('express')();    
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
 
    app.get('/signup',function(req,res){      
    res.sendFile(path.join(__dirname,'/signup.html'));
    });

so if u request like http://127.0.0.1:8080/signup that it will render signup.html page under views folder.

1
  • 1
    Side note - you're missing path.join with string concatenation. You probably meant path.join(__dirname, 'signup.html'). If you just contact the two with the + operator the call to path.join is pointless, as it's executed on a single argument.
    – Mureinik
    May 10, 2020 at 12:27
4

After years, I want to add another approach by using a view engine in Express.js

var fs = require('fs');

app.get('/test', function(req, res, next) {
    var html = fs.readFileSync('./html/test.html', 'utf8')
    res.render('test', { html: html })
    // or res.send(html)
})

Then, do that in your views/test if you choose res.render method at the above code (I'm writing in EJS format):

<%- locals.html %>

That's all.

In this way, you don't need to break your View Engine arrangements.

1

The "../" is considered malicious and will result in ForbiddenError: Forbidden at SendStream.error... exception.

The way to go is using a path module:

var path = require('path');
res.sendFile(path.resolve('views/auth/success.html'));
1
var app = express();

app.get('/test', function(req, res) {
  res.sendFile(__dirname + "/view/test.html")
});

Here __dirname, gives you the current path where your files are saved. So in res.sendFile(), we first tell our current location by __dirname + (then we locate the specific file which should we shown on the home page i. e ) "vies/test.html".

0

Follow this simple process and send html file -> res.sendfile("views/home.html"); // don't use capitla latter F with sendFile you must be use small letter f example : sendfile();

1
0
In Controllers -> use this in get all routes in index.js

To render html
const router = require('express').Router()
const path = require('path')`enter code here`


router.get('/',(req,res)=>{
  res.sendFile(path.join(__dirname,'/../views/test.html'))
})








To render EJS:
In server.js
const express = require('express');
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'))
app.use(bodyParser.json()) 
app.set('view engine','ejs')


In Controller- index.js
const express = require('express')
const app = express()
const router = require('express').Router();
const path = require('path')


router.get('/',(req,res)=>{
res.render('test')
})
1
  • Please do not format your entire answer as a code block.
    – DaveL17
    Jul 21 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.