使用ID作为快速javascript中的参数进行路由

问题描述

我有一个课程const columns = [ { title: "First Name",dataIndex: "firstName",className: "col-first-name",render: (text,record) => ( <Link to={"/athletes/" + record.id}>{text}</Link> ),},{ title: "Last Name",dataIndex: "lastName",className: "col-last-name" },{ title: "Email",dataIndex: "email",className: "col-email",} ];

Poll

一个数组

let id = 0;

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

在此数组中,保存了来自类const polls = [];

的对象

使用app.post方法,我生成一个新的Poll对象

Poll

现在,我想在app.get方法中使用id参数浏览不同的民意调查。

例如:localhost:3000 / polls / 2(id)

在polls /之后如何设置参数ID?

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 });
});

解决方法

Express允许您使用路由参数创建路由。

在您的情况下,您希望将轮询ID作为请求参数, 这样您就可以像这样在函数内部访问它:

app.get('/polls/:id',function(req,res){
  res.json({ id: req.params.id });
});