Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get id from url in express, param and query doesnt seem to work

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

like image 214
jyoti Avatar asked Feb 01 '14 11:02

jyoti


People also ask

How do I get params ID?

Use the useParams() hook to get the ID from a URL in React, e.g. const params = useParams() . The useParams hook returns an object of key-value pairs of the dynamic params from the current URL that were matched by the Route path. Copied!

What is req params ID in Express?

The req. params property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /student/:id, then the “id” property is available as req.params.id. This object defaults to {}. Syntax: req.params.


2 Answers

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

like image 122
grebneke Avatar answered Sep 25 '22 04:09

grebneke


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.

like image 24
SnapShot Avatar answered Sep 23 '22 04:09

SnapShot