Send a parameter along with sendfile - node.js

I am using nodejs
i have this code
var someparameter ="teststst";
var fileLocation = path.resolve(__dirname + '/../public/resetpassword.html');
console.log(fileLocation);
res.sendfile(fileLocation);
I want to send someparameter in resetpassword.html
Can anybody tell me how to do this ?
Thanks

You can't. (not without an engine)
Passing parameters to the html won't have any effect (and isnt possible)
You can use a template engine such as jade (or EJS if you want to stay with HTML)
Defined as:
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
And than you can 'render' view with parameters:
app.get('/', function(req, res){
res.render('index', {
users: users,
title: "EJS example",
header: "Some users"
});
});
Usaful Info:
EJS templates
Use EJS to Template Your Node Application

Related

Node.js Express rendering any *.jade

I have a test node.js server running the following code:
var app = require('express')();
app.set('views', __dirname + '/public');
app.set('view engine', 'jade');
app.get('/', function(req, res) {
res.render('index.jade', {name: "Test data."});
});
app.listen(3000);
This code works find. I'm wondering what the best practices are for choosing a .jade file based upon the url without hard-coding it, kind of like you might for html files using express.static. Of course, I don't want there to be a direct path correlation either (instead assigning different routes to different directories or groups of directories.) There doesn't seem to be a whole lot of solid information on the subject. Anything would be helpful. Thanks.
with utilization of splats you could do something like this:
var app = require('express')();
app.set('view engine', 'jade');
// /foo/Sam/path/to/view.jade yield a rendering of 'path/to/view.jade' with name: 'Sam'
app.get('/foo/:name/*.*', function(req, res) {
res.render(req.params.join('.'), {name: req.params.name});
});
app.listen(3000);

Get request url in server.js file. Node.js

I have server.js file where i define my server and all settings.
And i need to define request url before declaring those settings. Because i need to define them depend on request url.
An example:
var siteDir = ((app.route).lastIndexOf('/admin', 0) === 0) ? '/admin' : '/client';
app.engine('ejs', require('ejs-locals'));
app.set('views', __dirname + ('/template' + siteDir));
app.set('view engine', 'ejs');
So, if request url begins with 'admin' i will load templates from admin folder, otherwise from client.
My current implementation doesn't work, because app.route always returns '/'.
What can i do here. Please give me some advises. Thanks in advanced.
You cannot set the views directory per request with Express, which is what you're trying to do.
But you can use subdirectories in your calls to res.render():
app.get('/admin/', function(req, res) {
res.render('admin/index'); // renders '__dirname + /template/admin/index.ejs'
});
app.get('/', function(req, res) {
res.render('client/index'); // renders '__dirname + /template/client/index.ejs'
});
you can write your own middleware for this.
Something like this:
var siteDir = "/client"; //default case;
app.use(function(req,res,next){
if(req.path == '/admin') siteDir = '/admin';
else siteDir = '/client';
next();
});
app.engine('ejs', require('ejs-locals'));
app.set('views', __dirname + ('/template' + siteDir));
app.set('view engine', 'ejs');

Failed to lookup view in node.js ejs template while the template is only just renamed

I have a node.js application rendering in ejs 3 template.
let 's say -there is one template, course.ejs, it used to work well in node.js.
res.render('course', locals);
However, today when I tried to change the content, let 's say - course.ejs, it doesn't take effect, there is no error with node.js application and the data passed to the template is all right.
I even copy-pasted the content of this template, and make a new template with a different name - course1.ejs. and change my code to
res.render('course1', locals);
then when the app runs again, it pops up a error saying
Error: Failed to lookup view "course1" template.
The code in node.js and template are all right, it is supposed to work in the ways above. Why it doesn't work now. I have my ejs version 0.8.3, while express in 3.1.0 and node.js in 0.10.0
This is my app configuration.
app.configure(function(){
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('views',__dirname+'/views');
app.use(express.favicon(__dirname + '/public/favicon.ico'));
app.use(express.compress({
filter: function (req, res) {
return /json|text|javascript|css/.test(res.getHeader('Content-Type'));
},
level: 9
}));
app.use(express.bodyParser({uploadDir:__dirname+'/public/uploads',keepExtensions: true,limit: '50mb'}));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
cookie: { maxAge: 24 * 60 * 60 * 1000 }
,store: sessionStore
,secret: config.sessionSecret
,key: 'express.sid'
,clear_interval: 3600
}));
app.use(express.csrf());
app.use(function(req, res, next){
res.locals.token = req.session._csrf;
next();
});
app.use(express.static(__dirname+'/public'));
}
my static files is in the public folder, and all the templates are in the view folder.
I wonder has anyone met this kind of problem before
I don't think this configuration can work if your templates have the .ejs extension:
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
Using that configuration, Express will look for TEMPLATENAME.html when you call res.render('TEMPLATENAME', ...), and not TEMPLATENAME.ejs. For that, you need this:
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
So that's the course1 part solved: Express was looking for course1.html, which it couldn't find, so it would generate the error you got (Failed to lookup view...).
However, I don't see how rendering course.ejs could have worked. Perhaps you have another route which is handling the request you're testing? Or you have a course.html in the views folder (besides the course.ejs)?

Subfolder views expressjs 3x /nodejs

How can I use a subfolder for my 'views'?
In the main 'app.js' I've set the root folder for the views like so:
app.configure(function(){
app.set('view engine', 'jade');
app.set('views', __dirname + '/apps' );
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/apps' ));
app.use(app.router);
});
And my controller loos like this:
module.exports = function(req, res, base) {
res.render( 'hello/views/');
};
The folder looks like this:
./apps/hello/views/index.js
But still it can't find it. "ERROR: Failed to lookup view "hello/views"
Thanks!
Actually, I made a vastly better solution.
In the app configuration I just set the default view like so:"
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
Later on I inlcude a boot.js (based on the mvc example of expressjs ) in which I include the following:
// allow specifying the view engine
if (obj.engine) app.set('view engine', obj.engine);
app.set('views', __dirname + '/../apps/' + name + '/views');
This will override the view folder to the one specified in the folder 'apps/xxx/views' and will even allow you to specify a new viewtype in the root of that folder like so:
// filename = /apps/hello/index.js
exports.engine = 'jade';
// Render the indexpage
exports.index = function(req, res, next){
res.render('hello');
};
I am surprised that your self answer works, since you should be telling express to render a particular view, and hello/views is a folder. However I'm not familiar with the code pattern you're using for your controller (the base argument is what's throwing me off, since Express middleware uses function(req,res,next).)
My routes look like this:
app.set('views', __dirname + '/apps' );
...
app.get('/hello', function(req,res){
res.render('hello/views/index')
});
In this case ./apps/hello/views/index.jade is a jade file, not a javascript file. If your templates are javascript, perhaps you should set view engine to something other than jade.
You can set views as array of paths
app.set('views', [path.join(__dirname, 'views/users/'), path.join(__dirname, 'views')])
You can check the resulting paths using app.get('views'); which should return an array.
[/server/views/users/, /server/views]
Express will search through the array for available paths. You can then render with just the file name like this
res.render( 'index');
res.render( 'profile');
I fixed this problem by setting the basis view to the root of the directory like so:
app.set('views', __dirname);
And the added the folders from the root on in the controller like so:
res.render( 'apps/hello/views/');

Express JS not rendering jade template

I'm going to keep this short, I'm just trying to render a jade template using express js.
I'm using express 3.0.0rc5 and jade 0.27.6.
Here's my jade templates, the layout:
// test-layout.jade
doctype 5
html
head
title My title
block head
body
#content
block content
And the index:
// test-index.jade
extends test-layout
block head
script(src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js")
block content
h1 My page
Here's some excerpts from app.js:
var app = express();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.get('/test-jade', function(req, res) {
res.render('test-index', {}, function(err, html) {
});
});
app.get('/test', function(req, res) {
res.send('this works');
});
Now whenever I try to go to http://myurl.com/test-jade the browser just hangs and timesout without showing any output in the console (even though I'm in dev mode).
However when I go to http://myurl.com/test I see 'this works'.
I feel like I'm missing something really simple here, I'm currently upgrading from 2.5 to 3.0.
Thanks in advance if anyone has advice.
Is it the blank call back?
res.render('test-index', {}, function(err, html) {
});
In my app I'm using
res.render('test-index', {});

Resources