nodejs send html file to client

209.6k views Asked by At

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>
7

There are 7 answers

2
Tim Brown On BEST ANSWER

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.

1
Divya Balaji On
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')
})
0
efkan On

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.

0
M22 On

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'));
0
Gaurav Tripathi On
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".

1
Adiii On

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
Ontor Hazary On

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();