Doubt with GET sending data

1

I have a list of users:

<link>user1<link>
<link>user2<link>
<link>user3<link>
.
.
etc.

When I click on those links, the URL changes, for example: miAplicacion/user1 , miAplicacion/user2 ... etcetera.

On my server I already have the GET static for the users:

app.get('/user1', function(req, res, next) {
app.get('/user2', function(req, res, next) {
app.get('/user3', function(req, res, next) {

How to make it dynamic, instead of static?

although I do not need precisely in nodejs, because I believe that this form is the same in several languages.

    
asked by hubman 25.01.2017 в 01:20
source

2 answers

1

Try this:

app.get('/user/:id', function(req, res) {
   var idUser = req.params.id;
});

Instead of having several functions app.get() , better replace them with just one. to the above works you just have to pass the id of the user that you want, then the links should be like this: /user/1 or /user/238 . In any case, the variable 'idUser' should retrieve the id that you pass by URL.

    
answered by 25.01.2017 / 01:56
source
1

It would be enough to define a single endpoint on the server that receives dynamic parameters. The endpoint should be something specific, for example an endpoint for users, as in your case, for node express js would be something like:

app.get('/user/:id', (req, res) => {
  const id = req.params.id;
  db.findById(id, (err, user) => {
    if(err) return res.status(500).end('Error ocurred on querying db');
    // Renderizar algun template de usuarios:
    return res.status(200).render('user_template', user.toJSON());
  });
});

In this way, any requested route that complies with the pattern /user/something by method GET will be handled by the endpoint above. For more information, see the express documentation .

Regarding the client side, you just have to define a way to make your users enter this endpoint, either through links:

<a href="/user/1">User 1</a>

or through ajax:

$.ajax({
  url: '/user/' + id,
  type: 'GET',
  .
  .
  .
});
    
answered by 25.01.2017 в 02:27