how can i render html file in node.js - javascript

i have tried to render html file but i got this error . i have login.html within public folder.how to render html file.thanks in advance.
my server side coding
var express = require('express');
var app = express();
app.configure(function(){
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
});
app.get('/', function(req, res) {
res.render('login.html');
});
app.listen(8000)
Error: Failed to lookup view "login.html"
at Function.render (/home/aware/local/src/node_modules/express/lib/application.js:493:17)
at ServerResponse.render (/home/aware/local/src/node_modules/express/lib/response.js:753:7)
at /home/aware/local/src/health/demo2.js:17:9
at callbacks (/home/aware/local/src/node_modules/express/lib/router/index.js:161:37)
at param (/home/aware/local/src/node_modules/express/lib/router/index.js:135:11)
at pass (/home/aware/local/src/node_modules/express/lib/router/index.js:142:5)
at Router._dispatch (/home/aware/local/src/node_modules/express/lib/router/index.js:170:5)
at Object.router [as handle] (/home/aware/local/src/node_modules/express/lib/router/index.js:33:10)
at next (/home/aware/local/src/node_modules/express/node_modules/connect/lib/proto.js:199:15)
at resume (/home/aware/local/src/node_modules/express/node_modules/connect/lib/middleware/static.js:60:7)

The closest you can get to using html for node views is EJS (Embedded JavaScript)
This way you write your normal HTML, pass your data through node and display them using tags like: <%= var %>
http://embeddedjs.com/
https://github.com/visionmedia/ejs

You can render HTML page with Nodejs using Embedded JavaScript(ejs).
here you can go through -the Documentation of ejs
for using ejs, first of you create directory with the name views, In that directory create a file with .ejs extension.

The files you keep inside your public folder will not be rendered because they are set as static, so they will be served as is. All other files outside of this will be rendered. Remember to set the rendering engine.

I just came in contact with connect today & wanted to solve a simillar issue, serving a simple HTML file. In my case, I wanted to display a 404 when any previous middlewares hadn't finished the request.
I create a function, show404 and then you can do something like app.use(show404). Here's my CoffeScript for that mostly inspired in connect errorHandler source code.
show404 = (req, res, next) ->
res.statusCode = 404
res.setHeader 'Content-Type', 'text/html; charset=utf-8'
html_path = require("path").resolve('.tmp/404.html')
require('fs').readFile html_path, (err, data)->
throw err if err
console.log "DATA:", data
res.end data

Related

Set Home Page in Express

I have some server side code in node js, which creates a express js object and runs the server. The app loads the index.html page which is inside the public folder. I have never written the code to serve the home page (mention below), still it works.
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/index.html'));
});
I have not written this code so how does the index.html gets rendered. My understanding says express JS looks for the first instance of index.html page in all the static folders declared in the code and renders it, in my case the static folder is "publimc" and it has index.html at the root level.
server code follows below, which I have written.
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/publimc'));
app.use(bodyParser.json());
app.get('/contactlist', function (req, res) {
console.log('I received a GET request');
db.contactlist.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.listen(8000);
console.log("Server running on port 8000");
The home page is rendered as part of the express.static middleware default options.
To disable this logic, set express.static(..., { index: false }).
If you want to change the file served as a home page, set express.static(..., { index: 'yourfile.html' }).
What this option does, in fact, is attempt to serve an index page with given file name for each directory in your public folder, so if you have public/foo/index.html then it will get served when requesting /foo/ path.

How do I properly set routes up for a Single Page App using Express.js?

I am attempting to build a single page app using Express.js. On my index.html page, I have a basic form, which upon submit will make a request to an API, retrieve the data, parse it, and then I want to render the parsed data as a list of links. Right now I am able to render the index page, and I can make the submission call to the API from the form that I added to the page. What I am confused about is how to properly redirect the data I get from the API call and then render it on the same page. I've built simple apps using Express before where there were multiple views, but never a single page app. For those apps, I know that for the response you could call something like res.render('name of view to render', data), but that is not working in this case. I've tried to find some solutions through this site and via the Express docs, but I have not seen anything that didn't also include using another framework like Angular. For the purposes of this app, I need to not include any additional frameworks, and I am a bit lost.
My function for calling the API looks like this right now. When it is called, I am directed to a page that just has the json displayed
app.use(express.static(path.join(__dirname, '/public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/', express.static(path.join(__dirname, 'public')));
app.get('/search', function(req, res) {
var title = req.query.movieTitle;
var url = 'http://www.omdbapi.com/?s=' + title;
request(url, function (err, response, body) {
var results = JSON.parse(body);
var movieTitles = results.Search;
console.log(movieTitles);
res.send(movieTitles);
});
});
The basic thing you have to do is:
define routes which your back-end app has to respond with the spa
send your "skeleton" file to the response on that routes
Example code:
const handler = (req, res) => res.send(path.join(__dirname, "path/to/your/index.html"))
const routes = ["/", "/hello", "/world"]
routes.forEach( route => app.get(route, handler) )
This should get you started

Nodejs, expressjs - how to serve delayed response

I am building a webservice, for which i am using nodejs, phantomjs and expressjs. I am learning all the three.
I want to serve a delayed response to the clients after processing their query. Like for example,
I am processing certain inputs from my client, then, i want to process the data at the backend which will take approx 10 sec on an avg. Then i wanted to serve this page to the client.
Is it possible in node to send multiple responses to the same request or delayed responses so that the template will automatically update the contents.
Or , should i use the same method , like store the json in a file in the server , then serve the page with ajax which will query the page.
please help me. here is the code which i wrote ,
app-server.js(the main file):
// import express module
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// define all required template files to be served and also define the template engine
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
// Useful modules
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// import the routes
require('./router')(app);
app.listen(8080);
router.js:
var crypto = require('crypto');
var express = require('express');
module.exports = function (app) {
// define the static routes.
app.use('/static', express.static('./static'));
app.use('/media', express.static('./media'));
//defining the controller.
var parserlib = require('./controller.js')
// Define the home root path
app.get('/', function (req, res) {
// shows the home search page.
res.render('index', {content:'template success'});
});
app.get('/search', function(req, res){
res.redirect('/');
});
app.post('/search', parserlib.parserlib);
}
controller.js:
var crypto = require('crypto');
var path = require('path')
var childProcess = require('child_process')
exports.parserlib= function(req, res){
var output = '';
var url = req.body.search_url;
var childArgs = [
path.join(__dirname, 'external-script.js'),
url,
]
// execute the script in a separate thread.
childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
// handle results
console.log(stdout);
output = stdout;
//console.log(err);
//res.send(output);
});
//res.send(output);
};
so , what i want to see is, first send a response to client stating that its loading, then i want to update the with processed data. In other languages its not possible to send multiple responses. Not sure about nodejs.
Also, do i have to store the json output from the processed lib to a file and then use ajax to query ? or is it possible to directly update the json object to the client ?
Thanks
This is just not how HTTP works. The clients won't expect it. This has nothing to do with Node or any other framework. The way to do what you're attempting is to actually send a response that the thing is loading, and then have some other mechanism for reporting state.
As an example, you might design a RESTful API. In that RESTful API you might define a endpoint for creating new things:
POST /api/things
The client would post data to that to create a new thing. The response should be something that provides a location of the newly created resource, for example an HTTP 301 to /api/things/1.
If the user goes to /api/things/1 and the thing isn't done getting made yet, then you can either do a temporary redirect (303) to /api/things/1/status which provides some helpful status information, or just issue a 404.
If you actually want to send back server-side pushes of status information, then you should be looking at WebSockets or a pure Socket API of some kind, neither of which is provided by Express, but both of which are available in Node (checkout the socket.io library and the net core library)

why do I get Error: ENOENT open error when trying to render a doT.js view

I am trying out doT.js for the first time and have written a very basic server setup:
'use strict';
var express = require('express');
var app = express();
var doT = require('express-dot');
var pub = __dirname+'/public';
var vws = __dirname+'/views';
app.set('views', vws);
app.set('view engine', 'dot');
app.engine('html', doT.__express);
app.use('/css',express.static(pub + '/css'));
app.use('/img',express.static(pub + '/imgs'));
app.use('/js',express.static(pub + '/js'));
app.get('/', function(req, res){
res.render(vws + '/index.html', { title: 'dynamic title' });
});
app.listen(8080);
console.log('Server running on port 8080');
When I run the server and goto myaddress:8080 I get the following error:
Error: ENOENT, open '/home/myproject/views/layout.html'
If I try calling index.html with res.sendFile it works (although of course I can't pass variables that way)
res.sendFile(vws + '/index.html')
Where am I going wrong?
Why am i getting an error which seems to relate to a failed attempt at opening "layout.html" when no example I have seen mentions such a file?
I need to use res.render in order to pass variables to the template, but all the examples I have found do it the same way I tried in my first attempt.
dot.js isn't yet integrated with express 4.0's view engine middleware hook.
Swig is a similar application that is. It isn't quite as fast as dot.js, but for me it has a great balance of speed and features with an extremely intuitive syntax.
Full disclosure: I like swig.

Loading .js files on client side with page served by Node JS

I have the following simple JS file, which will look familiar to anyone who's used Socket.IO with NodeJS and the Express framework:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(8374);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
In index.html, I have the following line of code:
<script src="/socket.io/socket.io.js"></script>
I have done some experimenting with pathnames and serving/mounting and I still don't really understand how this client-side line manages to work. The answer to this question says that by listening to the server, io handles all incoming Socket.IO requests.
...
My question is: Can this be done for other client-side JS files?
For example, is there some easy way to bundle up JQuery so that it can be handled in the same way? At the moment I can put the file in a folder like public and use Express' app.use() method so that in index.html I can include this line:
<script src="/public/jquery-1.9.1.js"></script>
Is there a way to manage JQuery as a dependency as we can with NodeJS?
I'm thinking the end result would look something like this:
SERVER-SIDE:
var jquery = require('jquery');
CLIENT-SIDE:
<script src="jquery/jquery-1.9.1.js"></script>
I'm not too sure about using modules to host specific files, but it would be more time-efficient to just host the file when it's requested:
app.get("/", function (req, res) {
res.sendfile(__dirname + "/index.html");
});
app.get("/public/jquery-1.9.1.js", function (req, res) {
res.sendfile(__dirname + "/public/jquery-1.9.1.js");
});
I don't use Express, so please excuse any mistakes.
In express 2.x many used to use "dynamicHelpers" for this. Something like this in your app.js
app.dynamicHelpers({
scripts: function (){
return ['/js/jquery.min.js', '/js/jquery.ui.min.js']
}
})
In your layout using jade you'd do this.
- each s in scripts
script(type='text/javascript', src= s)
Now app.dynamicHelpers has been removed so in express 3.x you'll need to either create a simple module for this or just do it inline. with app.use within your configuration or specific environment if need be. something like.
app.use(function (req, res, next){
res.locals.scripts = ['/js/yourscript.js', '/js/yourotherscript.js']
next();
}
Using it in the jade layout would be the same. If I'm understanding you correctly that would be one way to include these scripts. Personally I'd rather included them statically though.

Categories

Resources