【问题标题】:app.get callback function does not trigger when use the same url as static file in express在 express 中使用与静态文件相同的 url 时,app.get 回调函数不会触发
【发布时间】:2016-03-03 00:50:09
【问题描述】:

我的服务器托管了一张静态图片,我可以在浏览器中访问它

例如:http://localhost:3000/media/foo.png

但是当我尝试使用一些额外的查询参数获取图像时,例如 http://localhost:3000/media/foo.png?var1=1&var2=2,它永远不会进入 app.get('/media') 的回调函数,它使用与 express.static 相同的 url。我想知道我的路由通配符映射是否错误?还是我无法设置具有相同名称的静态 url 的 get 方法?我该如何解决这个问题。

var express = require('express');
app.use('/media', express.static('libs'));
app.get('/media/*', function(req, res) {
  console.log('trigger');
});

【问题讨论】:

  • 试试这个app.all('/media/*', function(req, res) {?

标签: node.js express


【解决方案1】:

您需要在use:static 之前声明get:media 并检查查询参数:

app.get('/media/*', function(req, res, next) {
  if (Object.keys(req.query).length===2) {
    // do something
    console.log(req.query)
    res.end('Well, there are query parameters in the URL...')
  } else {
    next() // Ok, try static
  }
})

app.use('/media', express.static('libs'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-21
    • 2021-08-11
    • 2011-11-23
    • 2015-03-29
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    相关资源
    最近更新 更多