【问题标题】:Rest api implementation with parameter using JetBrains WebStorm + node.js + express使用 JetBrains WebStorm + node.js + express 实现带参数的 Rest api 实现
【发布时间】:2016-07-16 10:40:05
【问题描述】:

首先,我使用 JetBrains WebStorm 并用于创建 Node.js Express App 项目。

我的修改位于 app.js

app.get('/api/restaurants', function(req, res) {
  console.log("Parameter[0]", req.params.restaurant_id);
  res.json({
    '01010112D8139F13': '0ao123r1'
  });
});
app.get('/api/restaurants/:id', function(req, res) {
  console.log("Parameter[1]", req.params.restaurant_id);
  res.json({
    'message': 'worked?'
  });
});

我在 chrome 上使用邮递员插件来测试我的 api,如果没有由 router.route('/restaurants') 而不是 router.route 路由,我无法访问 localhost:3000/api/restaurants?restaurant_id=01010112D8139F13 ('/restaurants/:restaurant_id')

在控制台我有:

GET /api/restaurants?id=01010112D8139F13 200 1.803 ms - 31

如果有人可以帮助我,在此先感谢。

【问题讨论】:

  • 您是否遇到特定错误?请不要将您的代码包含在屏幕截图中。而是将代码包含在问题本身中。请务必通过help center 停下来了解有关如何使用该网站的更多信息。特别是,查看how to ask 部分。欢迎来到 Stack Overflow,欢迎提问!
  • 没有错误,它只是由 router.route('/restaurants') 在日志中我收到 GET /api/restaurants/?restaurant_id=01010112D8139F13 200 1.803 ms - 31

标签: node.js rest express


【解决方案1】:

restaurant_id 不是查询参数,而是路径中的可变部分。例如,/restaurants/01010112/restaurants/1 都由同一个 Web 请求处理程序处理,因为它们都符合 /restaurants/:restaurant_id 模式。

餐厅特定端点需要修改如下:

app.get('/api/restaurants/:id', function(req, res) {
  console.log("Parameter[1]", req.params.id);
  res.json({
    'message': 'worked?'
  });
});

并在控制台上使用以下网址:

/api/restaurants/01010112D8139F13

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多