nodejs send html file to client - node.js

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>

Try your code like this:
var app = express();
app.get('/test', function(req, res) {
res.sendFile('views/test.html', {root: __dirname })
});
Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.
You don't need the app.engine line, as that is handled internally by express.

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.

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.

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

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

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

Related

rendering in nodejs using express to html

I'm trying to get values from nodejs into HTML. I've seen lot of answers, but none of them is working.
here what I've done so far:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>
</head>
<body>
<div>
<a id="test" name="test"> <%=name%></a>
</div>
</body>
</html>
app.js
const express =require('express')
const app = express();
var os = require( 'os' );
var path = require('path')
const PORT = process.env.PORT ||2000;
app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname+'/index.html'))
})
app.get('/test', (req, res)=> {
var name = 454;
res.render( "/index.html", {name:name});
});
app.listen(2001)
I don't get what I'm doing wrong. but it doesn't work as expected.
any idea how may I solve this ?
thanks in advance !
First, create a folder views and put your index.ejs right there (though, I am not sure, the extension have to be .ejs).
Then set the engine with:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
And change your routing to:
app.get('/', (req,res) => {
res.render('index', { name: 'Test' });
});
Edit: I have used the express application generator and also checked Using template engines with Express.
Edit: According to the extension .ejs:
One thing to note is that all files in which ejs syntax are used in
must be saved with a .ejs extension [...]
Taken from Using EJS as a Template Engine in your Express App, not from the official docs.

Node.js + Express basic syntax explanation

I just started to see a beginner's tutorial on node.js. It uses the following:
const express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 80)
In the address bar it appears as localhost/test.html and not localhost/public/test.html - so in node.js you can control what's on the address bar regardless to the project structure, as it would've been in PHP?
Or app.use is only a one-time declaration, determining where the root is? such as htdocs or /var/www/html. Because you probably can't do both:
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/folder'));
With app.use You're attaching middleware.
If You want to use middleware in all routing logic You do it like:
app.use(middlewareHere);
Or You can define exact routing prefix when that middleware will be used:
app.use('/someRouteHere', middlewareHere);
So for Your case by doing:
app.use(express.static(__dirname + '/public'));
You're telling to express to it like:
app.use('/', express.static(__dirname + '/public'));
which means to call express.static middleware in all kinds of routings before processing next route handlers.
If You want to use it like: localhost/public/test.html
You've to attach middleware like this:
app.use('/public', express.static(__dirname + '/public'));
it's more secure that doing like:
app.use(express.static(__dirname + '/'));
because by defining exact route You're isolating static file handling to exact folder and other internal files that may keep sensible data (passwords, creds) cannot be accessible by static handler.
But best practice is keeping static files in assets folder and handling index.html as root route:
app.use('/assets', express.static(__dirname + '/assets'));
const indexFile = fs.readFileSync(__dirname + '/assets/index.html');
app.all('/', (req, res) => res.status(200).send(indexFile);
P.S. I recommend You to read official manual to understand routing logic.
UPDATE:
This part does not relate directly to Your question, it's for Your comment.
It's just an example. More detailed about how and why and etc read docs and google it. (:
Let's say You want to get data from database and inject that data to placeholders in .html files.
So it will be like this:
const ejs = require('ejs');
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);
app.set('views', __dirname + '/assets'); // since You want to keep html and other static files together
app.use('/assets', express.static(__dirname + '/assets'));
app.get('/profile', (req, res) => {
const userId = req.session.userId;
db.query(
'SELECT * FROM users WHERE id = ? LIMIT 1',
[userId],
(error, rows) => {
cons user = rows[0];
res.render('profile', {user}); // passing user object to view
});
});
And in Your profile.html :
<html>
</head>
<link rel="stylesheet" type="text/css" href="/assets/css/styles.css" />
</head>
<body>
Hello <b><%= user.username %></b>
</body>
</html>
Mini ejs tutorial about looping and etc in terms of php short open tags example:
<% let counter = 0; %>
<% while(counter < 100) { counter++; %>
<%= counter %>
<% } %>

Cant load css file

I'm trying to use the login templates (Took from: 50 Free HTML5 And CSS3 Login Forms For Your Website 201
My directory set up is like this :
-css
|
-- style.css
- js
|
-- index.js
|
index.html
The head of the index.html file looks:
<head>
<meta charset="UTF-8">
<title>Sign-Up/Login Form</title>
<link href='http://fonts.googleapis.com/css?family=Titillium+Web:400,300,600' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
and the body contains the includes scrips:
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
My node.js looks:
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// css
var path = require('path')
app.use(express.static(path.join(__dirname, 'public')));
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
/*
app.get('css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('css/style.css', {root: __dirname })
})
*/
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
When loading the html file I'm getting the error:
GET http://127.0.0.1:3001/css/style.css
I have tried to look for solution at:
Can not get CSS file
And created the public folder and copy the css folder inside, but it still doesnt work.
How can I load the css & js files ?
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
app.get('/css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('LoginTemplate/css/style.css', {root: __dirname })
})
app.get('/js/index.js', function (req, res) {
console.log('Get: js/index.js');
res.sendFile('LoginTemplate/js/index.js', {root: __dirname })
})
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
Everything looks good in your code and folder setup. From the URL you are posting (http://127.0.0.1:3001/css/style.css), I am guessing that the error lies in your server instance. Check the definition files and make sure that the server has permission to read css/style.css.
I have run into this problem when the file and folder do not have the right permissions. A quick check for this is running something similar to sudo chmod -R 0777 [path_to_your_project] (linux and Mac systems will use this command). This command gives full access to all users and guests to read, write and execute your files and is a quick way to verify whether the problem is user rights.
I have also run into this same problem when my web server is not correctly configured. In those cases, I had accidentally allowed the web server to share all files in the root folder (eg: /var/www ), but not any sub folders, so (using the example) the folder /var/www/images would be parsed by the web server and seen as an area that is protected. In this case, the Web Server has access, but it refuses to serve the files based on the configuration rules.
I hope one of these two fixes helps direct you down the right path to a solution.
Good luck!

NodeJS+Express:As I use links to navigate I cannot load the CSSs

I am very novice at Node.
I made the server run as follows (index.js):
var express = require('express'),
views = require('./routes/views');
var app = express();
// Get an instance of router
//var router = express.Router();
//app.use(express.static(__dirname+'/routes/keenIO/assets/css'));
app.use('/', views);
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
I use the router in this way, setting also the, I guess correct ones, paths to the static content (views.js):
var express = require('express');
var path = require("path");
var router = express.Router();
router.use('/assets', express.static(__dirname+'/keenIO/assets'));
router.use('/specificAssets', express.static(__dirname+'/keenIO/examples'));
//app.use(express.static(__dirname+'/routes/keenIO/assets/css'));
router.get('/', function(req, res) {
//res.send('GET handler for /views route.');
var indexPatch = path.join(__dirname+'/keenIO/examples/connected-devices/index.html');
res.sendFile(indexPatch);
//res.send(__dirname);
});
router.get('/rules', function(req, res) {
//res.send('GET handler for /views route.');
var indexPatch = path.join(__dirname+'/keenIO/examples/connected-devices/rules.html');
res.sendFile(indexPatch);
//res.send(__dirname);
});
router.get('/json', function(req, res) {
//res.send('POST handler for /views route.');
var fs = require('fs');
//res.send('HOLA MUNDO');
var obj;
fs.readFile('network-big.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
res.send(obj);
});
});
module.exports = router;
So, In the .html file I use for example this to reach to the css, and similar to reach to the javascript files:
<link rel="stylesheet" type="text/css" href="assets/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="assets/css/keen-dashboards.css" />
<link rel="stylesheet" type="text/css" href="specificAssets/connected-devices/connected-devices.css" />
I start this and everything is fine, but as I try to load the same index.html for example clicking on a link ( with the path to it: specificAssets/connected-devices/index.html) it has no style at all.
EDITED 25/10/16 3:30 p.m:
Well, inspecting the element with Chrome, as I click on the links I get doubled one part of the patch, getting for some static resources http://localhost:3000/assets/assets/resource.{css/js}
But it appropriately loaded the first time I access to the .html with http://localhost:3000. I am confused...
Any advise will be very appreciated.
Best regards,
Iván
Create a proper structure and keep all your html files in a views folder and do it following way that will work for you And for styling just keep your css in html file only or keep them in same folder and require file in html Easiest way to do is to keep your html and style in same file
router.set('views', path.join(__dirname, 'views'));
router.get('/', function(req, res) {
res.render('index');
});
If you want to use a proper structure then you need to know this thing as well
Since .css files are static files you have to serve them to the clients. However, you do not serve static files as a express middleware. Add the following middleware to your express app and move the css folder under the public directory (you should create a public directory)
app.use(express.static(path.join(__dirname, 'public')));

how to send data to client with expressJS

How would I go into retrieving data from expressJS? That is without it getting overwritten, or redirecting a user.
<html>
<body>
<h1>Retrieved data</h1>
</body>
</html>
for example how would i go into adding it if the server side looks like this?
var express = require("express");
var app = express();
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
//how do i add data to the <h1> tag
});
app.listen(10022, function () {
console.log("server is up");
});
You wouldn't be able to do it with a .html file. You'd need an EJS file. The markup for that would look like this.
<html>
<body>
<h1>Retrieved <%= data %></h1>
</body>
</html>
Then you'll need the ejs module. Run the following NPM command.
npm install ejs
So change your index.html to index.ejs, make sure it's in a directory named views, and then modify your server side code to this.
var express = require("express");
var app = express();
app.set("view engine", "ejs");
app.get("/", function (req, res) {
res.render("index", {data: 'This is the data'});
});
app.listen(10022, function () {
console.log("server is up");
});
EJS is a templating language that converts to HTML, taking the data object you've passed in through your render method, rendering it server side, and then sending it to the browser.

Resources