I got the code below from some other resources, trying to work with Twitter api, but it throws me some error.
I couldn't understand how to resolve that. Sometimes the error will appear when I use callbacks twice, but nothing seems like that.
var express = require('express'),
app = express(),
server = require('http').createServer(app),
routes = require('./routes'),
io = require('socket.io').listen(server),
path = require('path'),
twitter = require('ntwitter');
app.configure(function()
{
app.set('port', process.env.PORT || 5000);
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(app.router);
app.use(express.static(path.join(__dirname, 'public'))); });
app.configure('development', function(){
app.use(express.errorHandler());
});
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
app.get('/', routes.index); var twit = new twitter({
twit.stream('statuses/filter', { locations: criteria }, function(stream) {
stream.on('data', function (data) {
var geo=false,latitude,longitude;
io.sockets.volatile.emit('tweets', {
});
});
});
index.js
exports.index = function(req, res){
res.render('index', { title: '', criteria:'' });
};
Errors I am getting:
Express server listening on port 5000
GET / 200 30ms - 8.43kb
_http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.res.setHeader (/home/jayasurya/Desktop/node-twitter-modules/TweetMapViewer/node_modules/connect/lib/patch.js:59:22)
at next (/home/jayasurya/Desktop/node-twitter-modules/TweetMapViewer/node_modules/connect/lib/proto.js:153:13)
at Function.app.handle (/home/jayasurya/Desktop/node-twitter-modules/TweetMapViewer/node_modules/connect/lib/proto.js:198:3)
at Server.app (/home/jayasurya/Desktop/node-twitter-modules/TweetMapViewer/node_modules/connect/lib/connect.js:66:31)
at Manager.handleRequest (/home/jayasurya/Desktop/node-twitter-modules/TweetMapViewer/node_modules/socket.io/lib/manager.js:564:28)
at Server.<anonymous> (/home/jayasurya/Desktop/node-twitter-modules/TweetMapViewer/node_modules/socket.io/lib/manager.js:118:10)
at emitTwo (events.js:92:20)
at Server.emit (events.js:172:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:528:12)
Many thanks for any help!
Related
can't seem to figure out what the problem with my file structure might be. I'm using Aurelia as a front end and node for the server. I did a join that fixed some of the issues but now I'm getting this error:
Error: (SystemJS) Error: XHR error (404 Not Found) loading http://localhost:3000/src/main.js
Error loading http://localhost:3000/src/main.js
This is my server.js file:
var express = require('express'),
app = express(),
engines = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
bodyParser = require('body-parser');
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ useNewUrlParser: true }));
app.use('/scripts', express.static(require('path').join(__dirname, 'scripts')));
function errorHandler(err, req, res, next) {
console.log(err.message);
console.log(err.stack);
res.status(500).render('error_template', {err: err});
}
MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
assert.equal(null, err);
console.log('MongoDB connected!')
var db = client.db('todos');
app.get('/', function(req, res) {
res.render('index', {});
});
app.use(errorHandler);
});
var server = app.listen(3000, function() {
var port = server.address().port;
console.log("Express server listening on port %s.", port);
});
app.use('/scripts', express.static(require('path').join(__dirname, 'scripts')));
This line of code takes a local folder and makes it available through the express server. You need to do the same thing for your src folder
either with:
app.use('/src', express.static(require('path').join(__dirname, 'src')));
or:
app.use(express.static(require('path').join(__dirname, 'src')));
the first parameter allows you to name the directory it will be served as, which is usually the same.
And even though I didn't include the require('path').join(__dirname,... in the comment, it's good practice to include it.
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'm trying to separate server initiation and other calls from the core file(app.js) but when I try to run it, it issues me error that
http.createServer(app).listen(app.get('port'), function(){
^
TypeError: Object function (){ all code from app.js file }
has no method 'get'
This is app.js file.
/**
* Module dependencies.
*/
module.exports = function(){
var express = require('express');
var routes = require('./routes');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 4000);
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());
}
app.get('/', routes.index);
return app;
};
and this is server.js file.
var http = require('http'),
app = require('./app');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
using express#3.4.0
what am I missing OR doing wrong.. please help.
You have no reason to return a function into your app.js file, just return the express object:
var express = require('express');
var app = express();
// ... more variables
// ... the rest of your code
module.exports = app;
Then, the rest of your code into server.js will work fine.
Remember that module.exports works like a "return" into CommonJS (and therefore NodeJS).
See documentation.
You're passing a function to module.exports, so when you require('./app'), you need to call it like a function:
var http = require('http'),
app = require('./app')();
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
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 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!