ExpressJS:如何忽略路由中的公共静态文件?

发布于 2024-11-24 03:40:22 字数 351 浏览 0 评论 0原文

app.get("/:name?/:group?", function(req, res){...

正在匹配我的公共目录中的文件。因此,如果我包含样式表:

<link type="text/css" href="/stylesheets/style.css" />

节点将匹配 /stylesheets/style.css 并分配 namestylesheetsgroup样式.css

避免这种情况的最佳方法是什么?

app.get("/:name?/:group?", function(req, res){...

is matching files that are in my public directory. So if I include a stylesheet:

<link type="text/css" href="/stylesheets/style.css" />

Node will match /stylesheets/style.css and assign name the value stylesheets and group the value style.css.

What's the best way to avoid this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

刘备忘录 2024-12-01 03:40:22

最简单的事情可能是确保 Express 在路由器中间件之前运行静态提供程序中间件。您可以通过以下方式做到这一点:

app.use(express.static(__dirname + '/public'));
app.use(app.router);

这样静态文件将找到它并响应,并且路由器将不会被执行。我对路由器的默认位置(最后)也有类似的困惑,搞砸了我的咖啡脚本文件编译。仅供参考,此处有文档(在页面中搜索 app.router 你会看到一个解释性段落。

The easiest thing may be to make sure that express runs the static provider middleware prior to the router middleware. You can do this by doing:

app.use(express.static(__dirname + '/public'));
app.use(app.router);

That way the static file will find it and respond and the router won't be executed. I've had similar confusion with the router's default position (last) screwing up with my compilation of coffeescript files. FYI there are docs on this here (search the page for app.router and you'll see an explanatory paragraph.

岛徒 2024-12-01 03:40:22

对于任何可能需要它的人,我的解决方案是使用中间件。如果有人找到更好的解决方案,请告诉我!

public = ['images', 'javascripts', 'stylesheets', 'favicon.ico']

ignore = (req, res, next) ->
    if public.indexOf(req.params.name) != -1
        console.log "Ignoring static file: #{req.params.name}/#{req.params.group}"
        next('route')
    else
        next()

app.get "/:name?/:group?", ignore, (req, res) -> ...

For anyone who may need it, my solution was using Middleware. If anyone finds a better solution, please let me know!

public = ['images', 'javascripts', 'stylesheets', 'favicon.ico']

ignore = (req, res, next) ->
    if public.indexOf(req.params.name) != -1
        console.log "Ignoring static file: #{req.params.name}/#{req.params.group}"
        next('route')
    else
        next()

app.get "/:name?/:group?", ignore, (req, res) -> ...
≈。彩虹 2024-12-01 03:40:22

您还可以使用像 Nginx 这样的反向代理来为您处理静态文件。我相信许多专业的 Node / Ruby on Rails 设置都是这样做的。

You could also have a reverse proxy like Nginx handle the static files for you. I believe many professional Node / Ruby on Rails setups do it this way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文