繁体   English   中英

传递get参数表示路线

[英]Passing a get parameter to express route

我是nodejs的新手,表示并尝试构建简单的功能

我有这段代码可以成功地将我的get请求发送到适当的路由(在这种情况下,我编写了mysql查询的服务)

app.get('/requests', service.getRequests);

这适用于简单的get请求,例如http:// localhost:5000 / requests

我想知道如何从get请求中获取参数并将其传递到路由处理程序中?

例如: http:// localhost:5000 / requests?id = 123之类的东西,我想将id传递给service.getRequests函数,但是下面的方法不起作用-

app.get('/request',function(req,res){
  res.send(service.getRequests(req));
});

这是service.js(部分)的样子

exports.getRequests = function(req,res){
  //console.log(req.id);
  connection.connect()
  connection.query('SELECT * FROM table1 t where t.uid = ? LIMIT 10',[req.id], function (err, result, fields) {
    if (err) throw err
    res.json({ results: result });
  })
  connection.end()
}

编辑:我的问题专门不是如何获取GET参数,而是如何与res.send一起使用/如何使用此参数调用服务,特别是以下行-

app.get('/request',function(req,res){
  res.send(service.getRequests(req));
});

目前尚不清楚您使用哪个节点模块向PostgreSQL发送查询。 但是,假设您使用的是pg ,那么问题是您应该按如下所示放置参数:

SELECT * FROM table1 t where t.uid = $1 LIMIT 10

您可以将端点配置为采用这样的变量

HTTP://本地主机:5000 /请求/ 123

app.get('/request/:id',function(req,res){
    const id = req.params.id;
    console.log(id); // should display 123
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM