I'm playing around with Node.js and trying to make a Twitter API request.
I'm using an Express generated project, so my app.js
looks like that
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path')
, url = require('url');
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(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);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
And the index.js
like this
exports.index = function(req, res){
var username = 'Axiol';
option = {
protocol: 'http:',
host: 'api.twitter.com',
pathname: '/1/statuses/user_timeline.json',
query: { screen_name: username, count: 10 }
}
var twitterUrl = url.format(options);
console.log(twitterUrl);
};
Seems pretty fine, but, it always return me these errors
ReferenceError: url is not defined
at exports.index (/Users/Arnaud/Sites/badge/routes/index.js:17:20)
at callbacks (/Users/Arnaud/Sites/badge/node_modules/express/lib/router/index.js:161:37)
at param (/Users/Arnaud/Sites/badge/node_modules/express/lib/router/index.js:135:11)
at pass (/Users/Arnaud/Sites/badge/node_modules/express/lib/router/index.js:142:5)
at Router._dispatch (/Users/Arnaud/Sites/badge/node_modules/express/lib/router/index.js:170:5)
at Object.router (/Users/Arnaud/Sites/badge/node_modules/express/lib/router/index.js:33:10)
at next (/Users/Arnaud/Sites/badge/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.methodOverride [as handle] (/Users/Arnaud/Sites/badge/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:37:5)
at next (/Users/Arnaud/Sites/badge/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at multipart (/Users/Arnaud/Sites/badge/node_modules/express/node_modules/connect/lib/middleware/multipart.js:64:37)
Looks like it can't find url
, but it's well defined in app.js
...
Any idea ?
You need to do var url = require('url')
in your routes/index.js
file as well. I assume this is because of the nodejs module system. Each module is isolated, and the only thing visible from the outside are the things that you add to exports
(and globals, obviously). So local variables in a module is not available to other modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With