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')
Related
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' });
});
};
I am new to nodejs and am trying to code a quiz. Now I am able to fetch questions from collections usingdb.collection.find()
but my problem is I do not want to display all data(i.e. quiz questions) at once on the page. What I want is that I will display the first question and then when the user will click 'NEXT' button then the next question will be displayed.
Like say if there are 10 questions then at first only one question will be displayed and then when user clicks on 'NEXT' button then the second question will be displayed and so on.
I am short of ideas as to how to implement it.Please help.
Here is the relevant code from app.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, QuizProvider = require('./quizprovider').QuizProvider;
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {layout: false});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
var qProvider= new QuizProvider('localhost', 27017);
//Routes
......
......
//index
app.get('/', function(req, res){
qProvider.findAll(function(error, ques){
res.render('index', {
title: 'Questions',
myquiz:ques
});
});
});
app.listen(process.env.PORT || 3000);
Here is the relevant code from quizprovider.js
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
QuizProvider = function(host, port) {
this.db= new Db('quiz-db', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
.......
.......
//find all questions
QuizProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, quiz_collection) {
if( error ) callback(error)
else {
quiz_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
exports.QuizProvider = QuizProvider;
Here is the index.jade
extends layout
block content
h1= title
#Questions
- each mq in myquiz
div.mq
div.Question= mq.Question
a(href="/question/new")!= "Add New Question"
Ok friends I finally found a way to solve this problem. First I retrieved the records from myquiz to an array called data using Javascript in the JADE end and then displayed it using the following Jquery code in the JADE template:
$( "#myquestions" ).html(data[0]);
$( "#option1" ).html(data[1]);
$( "#option2" ).html(data[2]);
$( "#option3" ).html(data[3]);
$( "#option4" ).html(data[4]);
Reloading the page after a certain time by setting the setTimeout() function and calling a function from it.
Then each time the page reloads, get('/') will be fired. Increment the value of j(say) in get('/') and then pass it through res.render('index',{j: j})and use it in your index.jade .
I am working on a single page web app with node/angular and jade. I am fairly new to angular, and I wanted to know what I have to do with my app.js file so that my first page template loads from my angular file rather than from my jade template.
I structured my files as such:
public/
index.html
javascript/
img/
stylesheets/
routes/
index.js
views/
partials/
a.jade
b.jade
app.js
This is what my app.js looks like:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
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(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser('cookies monster')); // Cookie secret
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
/*
* Views
*/
app.get('/', routes.index);
app.get('/a', routes.a);
app.get('/b', routes.b);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
My index.js looks like this:
exports.index = function(req, res){
res.render('index', { title: 'Test Application' });
};
// View A
exports.a = function(req, res) {
res.render('partials/a', { layout: false, test: 'LOL' });
};
// View B
exports.b = function(req, res) {
res.render('partials/b', { layout: false, test: 'YOLO' });
};
When I run this, It does not use the index.html as the first page. How would I go about doing so, so that the initial page template is actually the index.html? I can't seem to find the answer anywhere.
You could return the actual index.html file from your router.
app.get('/', function(req, res, next){
return res.sendfile(app.get('public') + '/index.html');
});
I should note that I also put app.set('public', path.join(__dirname, 'public')); inside app.js for easy access to the public directory.
I am new to node and I wanted to try a simple app.post but I can't get it to work. my app.js and index.jade code is shown below. I am trying to get my app to print "hi" to the console when I enter data in the form and press submit but this is not happening.
**app.js**
/**enter code here
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express.createServer();
app.use(express.bodyParser());
// all environments
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(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('/users', user.list);
app.get('/george', function(req,res){
res.send('This is the random george page');
console.log("george");
});
app.get('/second', function(req,res){
res.render('secondpage');
});
app.get('/act', function(request, response){
console.log("hello");
});
app.post('/', function(request, response){
console.log("hi");
});
app.listen(3000);
console.log("Express server listening on port 3000");
**index.jade**
extends layout
block content
h1: a(href = 'second') George
p Welcome to your demosite George
form(method="post", action="/", name="act")
p
|Username
input(type="text", name="user")
p
|Password
input(type="text", name="pass")
p
input(type="submit", value="Submit")
First guess is everything in your jade file after the form tag needs 2 more leading spaces indent to make sure the input tags end up nested inside the form tag in the HTML. Your express JS code looks like it should work then.
I'm working with the new messages system in express 3 and figured this problem, when handling and validating forms. When submitting an invalid form, the submission fails, but there are no error messages displayed. When submitting it again, the error messages from the last request are shown. I tried using local sessions and Redis sessions, it's always the same. This is default express project:
app.js
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
app.response.message = function(type, msg){
// reference `req.session` via the `this.req` reference
var sess = this.req.session;
// simply add the msg to an array for later
sess.messages = sess.messages || [];
sess.messages.push({type: type, msg: msg});
return this;
};
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
console.log('req.session', req.session.messages);
var msgs = req.session.messages || [];
res.locals({
messages: msgs,
hasMessages: !! msgs.length
});
req.session.messages = [];
next();
});
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('*', function(req, res, next) {
res.message('hello', req.url);
next();
});
app.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
app.get('/hello', function(req, res) {
res.render('index', { title: 'Express' });
});
app.get('/world', function(req, res) {
res.render('index', { title: 'Express' });
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
index body addition:
<% if (hasMessages) { %>
<ul id="messages">
<% messages.forEach(function(msg){ %>
<li class="<%= msg.type %>"><%= msg.msg %></li>
<% }) %>
</ul>
<% } %>
/ there is no message
/hello shows '/'
/world shows '/hello'
reload shows '/world'
What's the problem here?
If you dont want to defer them you don't need to use sessions at all, that's the whole point in this case is to defer messages for the next render. By the time that middleware populates the "messages" and "hasMessages" it really doesn't have any unless the previous request populated them. This is typically used to defer msgs like "updated user successfully"