0

i have a class Poll

let id = 0;

class Poll {
  id;
  constructor(question) {
    this.id = id++;
    this.question = question;
  }
}

and a array

const polls = [];

in this array there are object saved from the Class Poll

With the app.post method i generate a new Poll Object

app.post('/polls', (req, res) => {
  res.statusCode = 201;
  console.log('req.body=', req.body);
  const poll = new Poll(req.body.question);
  polls.push(poll);
  res.json({ id: poll.id });
});

Now i want to browse the diffrent Poll with the id param in a app.get methode.

For example: localhost:3000/polls/2 (id)

How can i set the param id after polls/?

app.get('/polls/', (req, res) => {
    // search poll with id
 
});

1 Answers1

0

Express allows you to create routes with route parameters.

In your case, you would expect the poll-id as a request parameter, which allows you to access it inside the function like so:

app.get('/polls/:id', function(req , res){
  res.json({ id: req.params.id });
});
Carolin
  • 121
  • 4
  • Thank you for your answer. But its not working. This error shows up. Cannot GET /polls/1. But the poll with id 1 is existing – funnyboyfreak Nov 10 '20 at 08:27