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

只愿长相守 提交于 2019-12-08 14:34:09

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/21497639/how-to-get-id-from-url-in-express-param-and-query-doesnt-seem-to-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!