express 3.0.0 views not rendering - node.js

I am using the book "Smashing Node.js" by Guillermo Rauch. Chap. 12 sets up some views/routes before an authentication example. I have followed the tutorial to the best of my ability and searched (and searched) for my error.
//package.json
{
"name": "login"
,"version":"0.0.1"
,"main":"./index"
,"dependencies": {
"express": "3.0.0"
,"uglify-js" : "2.4.0"
,"mongodb":"1.3.19"
,"mongoose":"3.6.20"
,"bcrypt":"0.7.7"
,"jade":"0.35.0"
}
}
here is my index.js
/**module dependenies**/
var express = require('express')
, mongodb = require('mongodb');
//set up app
app = express();
//middleware
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'my secret'}));
//view options
app.set('view engine', 'jade');
//app.set('views', __dirname + '/views');
//app.set('view options', {layout: false});
//routes
//default route
app.get('/', function (req, res){
console.log('default');
res.render('index', {authenticated: false});
});
//login route
app.get('/login', function (req, res){
console.log('login');
res.render('login');
});
//signup route
app.get('/signup', function(req, res){
console.log('signup');
res.render('signup');
});
//listen
app.listen(3000);
in the same directory I have a folder of views/layout.jade, index.jade, signup.jade, login.jade I will show two.
'layout.jade'
doctype 5
html
head
title BN Login
body
.wrapper
block body
and index.jade
extends layout
block body
if (authenticated)
p Welcome back, #{me.first}
a(href="/logout") Logout
else
p Welcome visitor!
ul
li: a(href='/login') Login
li: a(href="/signup") Signup
the lines I have commented out did not help or are old.
The layout.jade renders. The console shows that the code is being read. No other view is rendered.
Thanks.

I think you have not used indentation correctly. In your index this :
extends layout
block body
if (authenticated)
...
else
should be :
extends layout
block body
if (authenticated)
...
else

Related

Json data for handlebars.js dissappears after post

I set the page title like so for handlebars to render:
// Registor
router.get('/register', function(req, res) {
req.session.title = "Register";
res.render('register', {
active: {
active_register: true
},
title: req.session.title
});
});
I then post:
router.post('/register', function(req, res) {
The page title disappears along with all data sent when rendering the page.
I want the title to stay. How?
I have already tried resetting the title many ways with res.
According to your question there is error in handlebars. For this you have add this lines in your app.js file or main file
app.set('views', __dirname + '/views/');
app.set('view engine', 'handlebars');
app.engine('handlebars', engines.handlebars);

express - How to path to express jade views

If I path to a view in ./views express will render it but it doesn't that for example ./views/api/login.jade and it send 500: Internal Server Error.
my codes:
/* GET api/... */
router.get('/login', function(req, res, next) {
res.render('api/login.jade', { title: 'Login' });
});
Thanks
You have to set the views path as well.
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
router.get('/login', function(req, res, next) {
res.render('api/login', { title: 'Login' });
});
step 1: you have to make sure you are using jade as the view engine.
app.set('view engine', 'jade');
step 2: set view path
app.set('views', __dirname);
or you can write it in every render call, res.render(__dirname+'api/login')
Step 3: do not write extension names
router.get('/login', function(req, res, next) {
res.render('api/login', { title: 'Login' });
});
P.S.
i recommend that you start using pug instead of jade since pug is jade 2.0

express res.redirect target page js not loaded

I am using Node.js + Express + Jade to demo some very simple pages. I got this problem for two days. I googled a lot, but cannot find answer. Basically, I redirect from a page to another. And on the target page, I have some socket.io code inside document.ready. The problem is from /pageone, the pagetwo is rendered correctly(but url in browser is still /pageone), but the code inside document.ready is not executed.
My router.js
app.post('/pageone', session, function(req, res){
res.redirect('/pagetwo');
});
app.get('/pagetwo', function(req, res){
res.render('pagetwo', { title: 'demo' });
});
My pagetwo jade
doctype
html
head
title #{title} - My Site
link(rel='stylesheet', href='/css/style.css')
script(type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js')
script(type='text/javascript' src='https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js')
script.
$(document).ready(function() {
alert("I am an alert box!");
});
body
h1 DEMO
The result is that I can see DEMO on the page but alert box is not showing. But if I directly visit /pagetwo, the alert box is showing.
Many thanks
////// EDITED //////
This is my app.js
var express = require('express')
, http = require('http')
, session = require('express-session');
var app = express();
var port = process.env.PORT || 8080;
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('port', port);
app.use(express.static(__dirname + '/public'));
app.use(session({ secret: 'gdfgsdrgesrgerge', cookie: { maxAge: 60000 }}))
require('./controller/router')(app);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
})
And this is my router.js
var express = require('express');
module.exports = function(app) {
app.get('/pageone', function(req, res){
res.render('pageone', { title: 'Welcome' });
});
app.post('/pageone', function(req, res){
res.redirect('/pagetwo');
});
app.get('/pagetwo', function(req, res){
res.render('pagetwo', { title: 'demo' });
});
};

nodejs, express and jade: problems with inserts from form to database

when i try to enter data in my jade form i get error message that says it is null. Can someone help me figuring out what the problem is?
app.js
var express = require('express');
var pg = require('pg');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
var conString = "postgres://abc:123#localhost/abc";
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only,
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//app.get('/', routes.index);
app.get('/', function (req, res) {
res.render('index',
{ title : 'Home' }
)
});
app.get('/users', user.list);
app.post('/', function(req, res){
var header = req.param('header', null); // second parameter is default
var body = req.param('body', null);
console.log(header);
console.log(body);
pg.connect(conString, function(err, client, done, request, response) {
client.on('drain', client.end.bind(client));//stänger av när alla queries är klara
client.query("INSERT INTO post(member_id, title, body) VALUES ('1', $1, $2)", [header, body], function(err, result){
if (err) {
console.log(err);
}
else{
res.send("success!");
}
});
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
index.jade
extends layout
block content
h1= title
p Welcome to #{title}
form(action='/',method='post')
input(type='text',id='header',placeholder='header')
input(type='text',id='body',placeholder='body')
input(type='submit',name='submit',value='Submit')
layout.jade
doctype html
html
head
title= title
link(rel='stylesheet',href='/stylesheets/style.css')
body
block content
p whaddup
However if I use curl --verbose -d 'header=abcd&body=1234' http://localhost:3000 it works fine, so im fairly certain it's the jade part, but i've no clue what's wrong. I am new to nodejs and all that :)
thanks in advance.
It's the name of a form control that is submitted with the data, not the id. As it is, the only value your form is submitting is that of the submit button.
Rather it should look like this:
input(type='text', name='header', placeholder='header')
input(type='text', name='body', placeholder='body')

Parsing url params in expressjs - angularjs application

Struck with routing issue in expressjs and AngularJs project.
It's not a single page application and I am not using any view engines such as jade.
We are just using plain HTML.
I am working on password reset functionality where user can reset the password by clicking a link provided by an email. So I assume there won't be any route change event in the context of Angular (Please correct me if I am wrong).
And my express configurations are as follows.
routes = require('./routes/index');
app.configure(function () {
app.use(express.static(__dirname + '/app'));
app.use('/css', express.static(__dirname + '/app/css'));
app.set('views', __dirname + '/app');
app.set("view options", { layout: false });
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.use(express.favicon());
//app.use(require('connect').bodyParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
// Routes
app.get('/', routes.index);
app.get('/resetpassword.html/:resetcode', function (req, res) {
console.log("reset code: " + req.params.resetcode);
res.render('resetpassword.html/' + req.params.resetcode);
});
app.get('/api', function (req, res) {
res.send('Ecomm API is running');
});
// JSON API
app.post('/registeruser', usersApi.registerUser);
app.post('/api/login', usersApi.logIn);
app.post('/api/addgame', gamesApi.addGame);
app.get('*', routes.index);
// Start server
app.listen(2221, function () {
console.log("Express server listening on port %d in %s mode", 2221, app.settings.env);
});
and index.js
exports.index = function(req, res){
res.render('home.html');
}; // Always rending index.html which needs to be fixed.
And app.js from AnghularJs as follows
app.config(function ($routeProvider) {
$routeProvider
.when('/', { templateUrl: 'home.html' })
.when('/resetpassword.html/:resetcode', { templateUrl: '/resetpassword.html', controller: 'ResetPasswordCtrl' })
.otherwise({ redirectTo: '/' });
});
I am getting 500 internal error or view not found error.
Any suggestions please.
You are concatenating the password to the view name that you pass to render hence why Express does not find the view and returns a 500 error. You need to pass the data as an additional parameter to the render function as an object:
res.render('resetpassword.html', {resetcode: req.params.resetcode} );
Then in your view use resetcode directly e.g.
<span><%= resetcode %></span>

Resources