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
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!
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.
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
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.
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