I just try to write a simple node.js application, but if I use the express-validator the site is just loading and do nothing :(
"waiting on localhost", after some time an "ERR_EMPTY_RESPONSE" error appears.
If i delete the app.use(expressValidator) the application works again.
var express = require('express'),
expressValidator = require("express-validator");
var app = express();
app.configure(function(){
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.bodyParser());
app.use(expressValidator);
});
app.get('/', function(req, res) {
console.log('get something get');
res.render('app.jade');
});
app.post('/', function(req, res){
console.log('get something post');
res.render('app.jade');
});
app.listen(process.env.PORT || 8080);
You need to call the expressValidator function to get it to return a middleware handler:
app.use(expressValidator());
^^ important!
Related
I'm trying to render an html page with express. Here's what I have so far:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.listen(3000, function() {
console.log('listening on PORT 3000');
})
app.get('/', function(req, res){
res.send('Home page!')
})
app.get('/events', function(req, res){
res.render('eventForm')
})
my file tree so far:
-Project
-node_modules
-public
index.html
-views
eventForm.html
I tried putting the eventForm.html in public as well but for some reason my server can't "find" it. I get the following error:
Error: Failed to lookup view "eventForm" in views directory "/Users/username/LearnProgramming/api_playground/stubhub/views"
set your views before setting view engine
app.set('views', path.join(__dirname, 'views'));
var express = require('express');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.listen(3000, function() {
console.log('listening on PORT 3000');
})
app.get('/', function(req, res){
res.send('Home page!')
})
app.get('/events', function(req, res){
res.render('eventForm')
})
app.use(express.static(__dirname + '/public'));
How about eventForm with .html?
I am using "express": "3.2.6", and nodeJS v0.10.25.
When running my app.js I get:
TypeError: Object #<IncomingMessage> has no method 'getConnection'
My app.js:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
//database connection
var connection = require('express-myconnection');
var mysql = require('mysql');
//all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
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());
}
/*------------------------------------------
connection peer, register as middleware
type koneksi : single,pool and request
-------------------------------------------*/
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
port : 3306, //port mysql
database:'db-test'
},'pool')
);
//routes
//app.get('/', routes.index);
app.get('/', routes.list);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
My index.js file looks like that:
/*
* GET home page.
*/
//exports.index = function(req, res){
// res.render('index', { title: 'Express' });
//};
/**
* returns all trade objects
*/
exports.list = function(req, res){
req.getConnection(function(err,connection){
connection.query('SELECT * FROM trades',function(err,rows) {
if(err)
console.log("Error Selecting : %s ",err );
res.render('customers',{page_title:"Customers - Node.js",data:rows});
});
});
};
I am getting the following exception:
Express server listening on port 3000
TypeError: Object #<IncomingMessage> has no method 'getConnection'
at exports.list (C:\Users\nodeWorkspace\Test\routes\index.js:14:6)
at callbacks (C:\Users\nodeWorkspace\Test\node_modules\express\lib\router\index.js:161:37)
at param (C:\Users\nodeWorkspace\Test\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Users\nodeWorkspace\Test\node_modules\express\lib\router\index.js:142:5)
at Router._dispatch (C:\Users\nodeWorkspace\Test\node_modules\express\lib\router\index.js:170:5)
at Object.router (C:\Users\nodeWorkspace\Test\node_modules\express\lib\router\index.js:33:10)
at next (C:\Users\nodeWorkspace\Test\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.methodOverride [as handle] (C:\Users\nodeWorkspace\Test\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:37:5)
at next (C:\Users\nodeWorkspace\Test\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at multipart (C:\Users\nodeWorkspace\Test\node_modules\express\node_modules\connect\lib\middleware\multipart.js:64:37)
[90mGET / [31m500 [90m59ms
Any recommendation what I am doing wrong?
I appreciate your answer!
Looks like you used example somethink like this: http://teknosains.com/i/simple-crud-nodejs-mysql but changed code sequence.
Move app.use(app.router); under declared app.get/app.post.
Also you can use other case of mysql integration as: https://www.npmjs.com/package/express-myconnection
I have some trouble to use Socket.io even just to test if a client is connected. I've tried many things and I think that my mistake is, maybe, when I do the app.get function. I have also tried to do this in an route js file but it wasn't conclusive neither. So here are my different codes :
App.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('mongodb://xxxxx:xxxxx#ds051067.mongolab.com:51067/jdo');
var app = express(),
server = http.createServer(app) ,
io = require('socket.io').listen(server);
// 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(express.cookieParser('This is secret'));
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());
}
io.sockets.on('connection', function (socket) {
console.log('Un client est connecté !');
});
// app.get('/', routes.index);
app.get('/users', user.list);
app.get('/deplacement',routes.deplacement);
app.get('/monCompte', routes.compte);
app.get('/connexion', routes.connexion);
app.get('/', function(req, res) {
res.render('index.jade');
});
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Index.jade
extends layout
block content
script(src="/socket.io/socket.io.js").
var socket = io.connect('http://localhost:3000');
});
PS : Sorry if my english is bad ^^
You can't use inline javascript in the same script tag as an included script.
extends layout
block content
script(src="/socket.io/socket.io.js")
script.
var socket = io.connect('http://localhost:3000');
I'm getting started on node JS and facing an issue with io lib, here the error :
ReferenceError: io is not defined
at exports.index (D:\dev\lib\index.js:9:5)
at callbacks (D:\dev\node_modules\express\lib\router\index.js:164:37)
at param (D:\dev\node_modules\express\lib\router\index.js:138:11)
at pass (D:\dev\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (D:\dev\node_modules\express\lib\router\index.js:1 73:5)
at Object.router (D:\dev\node_modules\express\lib\router\index.js:33:1 0)
at next (D:\dev\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.methodOverride [as handle] (D:\dev\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:49:5)
at next (D:\dev\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.urlencoded [as handle] (D:\dev\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:51:37)
Here is the content of my app.js file :
var express = require('express');
var path = require('path');
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
fs = require('fs');
app.set('port', process.env.PORT || 8080); 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.get('/', require('./lib').index);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
my file lib/index.js :
exports.index = function(req, res){
res.render('index');
io.sockets.on('connection', function (socket) {
socket.emit('message', 'welcome');
});
};
Can anyone help me?
You need to pass io to your route:
exports.index = function(io) {
return function(req,res) {
res.render('index');
io.sockets.on('connection', function (socket) {
socket.emit('message', 'welcome');
}
}
}
And then call it as a function in app.get:
app.get('/', require('./lib').index(io));
I'd recommend declaring the require('./lib') part with your other variables. This would allow for code reuse and better readability (which is relative to each person).
var /*other variables*/,
lib = require('./lib');
Then you could just do app.get('/', lib.index(io));
Just a thought.
I've got a small node.js application using the express framework, but for some reason I can't get my application to respond to POST requests. In the server log I simply get "POST / 404 5ms", and I can't figure out why.
EDIT: To clarify - My problem is that app.post doesn't seem to be doing anything
EDIT 2: I somehow managed to fix this last night, but now I can't figure out at what point i fixed it.
Node.js server code:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('chocolatechip'));
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());
}
//pages
//Landing page
app.get('/', routes.index);
app.post('/test',function(req,res){
console.log(req.body);
res.send("received post");
});
//return list containing users
//app.post('/users', user.list);
//return requested user
app.get('/users/:id', user.get);
//app.post('/users/login', user.login);
//server
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
On the actual webpage, I've got the following javascript code:
var login = $('#login');
var page = $('#page');
var register = $('#register');
var userField = login.find('.user');
var passField = login.find('.pass');
var confPassField = login.find('.confpass');
var form = $('.logform');
$('#formbutton').on('click',function(){
if(register.hasClass('hidden')){
login.addClass('hidden');
confPassField.val('');
var logDat = JSON.stringify(form.serializeArray);
userField.val('');
passField.val('');
page.html("Login form submitted");
$.post(
form.attr("action"),
{test:"test"},
function(data){
alert("Response: "+data)
}
);
}
If you are posting to / as your log is saying that you are "POST / 404 5ms", you need to change the following line:
app.get('/', routes.index);
to
app.all('/', routes.index);
This will allow a GET or POST to that route. You can also just use app.post() if you are only posting to that route. Hope this helps.
Docs here: http://expressjs.com/api.html#app.all
Make sure that 'form.attr("action")' is getting the proper URL. It seems that your form is posting to the index page rather than to '/test'. Maybe that should be changed to $('form').attr("action")
For me the problem was that I had my
app.post('/test', jsonParser, function (req, res) {
console.log(req);
res.send('Ok');
});
below this part added by express-generator to my app.js
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
By changing the order in the file I resolved this problem.