【问题标题】:Express 4 route not hitExpress 4 路线未命中
【发布时间】:2016-05-27 08:23:54
【问题描述】:

我正在运行 Express 4。在 app.js 中我得到了:

var products = require('./routes/products');
var app = express();
app.use('/products', products);

然后,在路线/产品中:

router.get('/', function(req, res) {
    //Some Code. Ok
});

router.get('/:code', function(req, res) {
    //Some code. Not hit
});

我的问题是第二条路由在使用 code 参数调用时永远不会命中,它总是命中 /

http://localhost:3000/products?code=123 转到 /

我做错了什么?

【问题讨论】:

  • 这不是你写路由器的方式:http://localhost:3000/products/123 应该能让你到达那里。否则,您将使用第一种形式,然后查看 req.query
  • @barry-johnson 以上评论是正确答案。
  • @barry-johnson 感谢您的回复。写下您的评论作为答案,将其标记为已解决
  • @barry-johnson 顺便问一下,如何设置路由以便接收代码作为查询字符串参数?
  • @Oscar - 我刚刚添加了一个答案,应该解释req.queryreq.params 处理它的方法。

标签: node.js express


【解决方案1】:

正如我在评论中提到的,路由器的编写方式,您可以像使用 http://localhost:3000/product/123 一样调用它,这将导致值 "123" 在您的处理程序中的 req.params.code 中可用。

要执行您想做的事情,您将使用您定义的第一个路由器,您已经将其绑定到您的应用程序的/products 路径。

router.get('/', function(req, res) {

    if (req.query.code !== undefined) {
        // do something here if there was a parameter
    } else {
        // your original '/products' code here...
        //Some Code. Ok
    }
});

基本上:req.params 用于编码到主 URL(即“?”左侧)的参数,而req.query 用于提取的查询字符串参数。

您可以阅读更多关于 req.query 工作原理的信息 - 即,它将查询字符串提取到 express doc for it 上的 req.query 对象中的方式。也值得阅读req.params,这样你就知道你的选择了。

【讨论】:

  • 非常感谢
【解决方案2】:
router.get('/:code', ...)

匹配类似的路由

http://localhost:3000/123

router.get() 路由匹配 URL 中的内容,而不是查询字符串中的内容。要将http://localhost:3000/products?code=123 处理为路由,您应该这样做:

router.get('/products', ...)` 

然后在您的路由处理程序中检查查询字符串以查看 code 的值。

 router.get('/products', function(req, res) {
      // access req.query.code here to get the value of `?code=123
      console.log(req.query.code);         // 123
 });

req.query here 的表达文档。

【讨论】:

    猜你喜欢
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多