Search Results

Search found 1 results on 1 pages for 'modfox'.

Page 1/1 | 1 

  • Expressjs route param as variable in main app

    - by MoDFoX
    For my app I have two route set up, app.get('/', routes.index); app.get('/:name', routes.index); I would like it to be so that if I don't specify a param, say just go to appurl.com (localhost:3000), it would load a default user, but if I do specify a param(localhost:3000/user), use that as the variable "username" in the following function (placed after my routes). (function getUser(){ var body = '', username = 'WillsonSM', options = { host: 'ws.audioscrobbler.com', port: 80, path: '/2.0/?method=user.gettopartists&user=' + username + '&format=json&limit=20&api_key=APIKEYGOESHERE' }; require('http').request(options, function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { body = JSON.parse(body); artists = body.topartists.artist; }); }).end(); })(); Along with this I have my route set up like so: exports.index = function(req, res){ res.render('index', { title: 'LasTube' }); username = req.params.name; console.log(username); }; unfortunately setting username there to req.params.name does not seem to be accessible from the main app function. My question is: How can I set expressjs/nodejs to use the parameter set via /name when available, and just use a default - in this example "WillsonSM" if not available. I've tried taking "username" out of the main app, and just leaving it in the function, but username becomes undefined, as it is inaccessible from the route, and the app will not run. I can spit out "username" via the routes console.log, so assigning it there is not an issue, but as I am new to expressjs, I am unaware of how I should go about doing this. I have tried all I can think of and find from looking around the internet. Also, if there is a better way of doing this, or I am doing something wrong, please let me know. If I've left out any information, just throw in a comment and I'll try to address it.

    Read the article

1