37

I have a url, i'm trying to get id but none of it is working req.params nor req.query

app.get('/test/:uid', function testfn(req, res, next) {
  debug('uid', req.params.uid);  // gives :uid
  debug('uid', req.query.uid);  // gives undefined      
});

I'm doing an ajax call like this

$(document).on('click', 'a.testlink', function(e) {
  $.ajax({
    type: "GET",
    url: '/test/:uid',
    success: function(var) {
      console.log('success');
    },
    error: function() {
      alert('Error occured');
    }
  });
  return false;
});

I'm using

app.use(express.json());
app.use(express.urlencoded());

instead of body parser

Sonicd300
  • 1,950
  • 1
  • 16
  • 22
jyoti
  • 443
  • 1
  • 5
  • 10
  • In your code, `app.get('test/uid:', test.collect);` should be `app.get('test/:uid', test.collect);`. Then you can use `req.params.uid` to get the uid value. – bnuhero Feb 01 '14 at 12:00
  • hi sorry, it is like that only, i made mistake while posting the question. Still its not taking the value – jyoti Feb 01 '14 at 12:02
  • Again in your code, you are using `req.param` instead of using `req.params`. – bnuhero Feb 01 '14 at 12:07
  • I'm doing debug('uid', req.param.uid); // which gives :uid when debugged – jyoti Feb 01 '14 at 12:17
  • It seems that you should use `test` instead of `test.collect` as the route handler function. – bnuhero Feb 01 '14 at 12:26

2 Answers2

58

Your code is working as expected: The ajax call specifies url: '/test/:uid' which is what puts :uid in req.params.uid.

Try sending something else: url: '/test/123' and req.params.uid will contain 123

grebneke
  • 4,414
  • 17
  • 24
11

Here is an example that will work. I will give step by step instructions from the start:

express myproject
cd myproject
npm install

Open app.js and add in the following somewhere in the file - maybe right before the line app.get('/test/:uid',test);

var test = function(req,res,next) {
  // do whatever logic is needed 
  res.end('Displaying information for uid ' + req.params.uid);
}
app.get('/test/:uid',test);

Now, open up a new terminal, make sure you are in the myproject directory and enter:

node app.js

Now you can visit http://localhost:3000/test/45 on the local machine and you should see:

Displaying information for uid 45

If you are not accessing from your local machine make sure to change the url above to match whatever server your node app is running on.

Also, this is just a simple example. You might be better off organizing everything by placing the routes in files similar to the routes directory example setup in a new install of an express app. You can find more detailed examples of this on the web like this one and this one. Also, one of the best explanations of organizing/reusing code in Node this I have seen is in the book NodeJS in Action.

Community
  • 1
  • 1
SnapShot
  • 5,464
  • 5
  • 42
  • 40