Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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){                 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> 
like image 818
user3044147 Avatar asked Dec 03 '13 08:12

user3044147


People also ask

How do I send an HTML file?

Copy the entire content of a page, either with Ctrl+A (Windows) / Cmd+A (Mac) or just use a mouse or a trackpad. Then, insert it into your Gmail's compose window and send it! The email should arrive in exactly the same shape as it was last seen leaving your inbox.

Can we use HTML in node JS?

js. So far we sent html code directly from the send(0 function in response object. For sending larger code, we definitely require to have a separate file for html code.


2 Answers

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.

like image 92
Tim Brown Avatar answered Oct 03 '22 22:10

Tim Brown


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.

like image 38
Adiii Avatar answered Oct 03 '22 22:10

Adiii