如何将中间件与express.static一起使用? [英] How can I use middleware alongside express.static?

查看:59
本文介绍了如何将中间件与express.static一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个nodejs应用程序,它通过express.static提供一个单页应用程序.一切正常,但是当我尝试创建一个简单的中间件时:

I have a nodejs application that serves a single page app via express.static. This all works fine, however when I try and create a simple piece of middleware:

app.use(function(req, res, next){
  console.log('%s %s', req.method, req.url);
  next();
});

app.use(express.static(path.join(__dirname, 'client')));

任何尝试从客户端加载内容的尝试都会失败,并显示以下信息:

any attempt to load content from client fails with:

TypeError: Object function (req, res, next){
  console.log('%s %s', req.method, req.url);
  next();
} has no method 'concat'

如果我在express.static调用之后使用中间件,则它可以正常工作-但不会调用静态内容.我需要设置中间件,以便任何Flash消息(来自Connect Flash)都可以Cookie的形式发送到静态内容.

If I use the middleware after the express.static call it works fine - but isn't called for static content. I need to setup the middleware so that any flash messages (from connect flash) can be sent as cookies to the static content.

有人知道我如何将中间件用于所有内容,包括静态内容吗?最终,我将提供两个文件夹,一个为公用文件夹,一个为私人文件夹(通过护照验证).

Does anyone know how I can use middleware for all content, including static content? Eventually I'll be serving two folders, one public and one private (authenticated via passport).

推荐答案

我对您的问题做了一个最小的实现,对我有用:

I've put together a minimal implementation of your question and it works for me:

var express = require('express')
var path = require('path')

var app = express()

app.use(function(req, res, next) {
    console.log('Middleware says %s %s', req.method, req.url);
  next();
})

app.use(express.static(path.join(__dirname, 'client')))

app.listen(8080, function() {
    console.log('server is ready')
})

然后我启动了服务器

$ node so.js
server is ready

并将http://localhost:8080/foo.txt加载到我的浏览器中

and loaded http://localhost:8080/foo.txt in my browser

Middleware says GET /foo.txt

我使用的是Express 3.6.0-如果您使用的是Express的旧版本,那么您很可能偶然发现了一个已修复的错误,类似于

I'm using Express 3.6.0 - if you're using an older version of Express then you may well have stumbled across a bug that's since been fixed, similar to this one. If updating doesn't solve your problem then I would recommend updating your question to contain more code, perhaps a runnable, yet minimal example of the issue. Hope this helps!

这篇关于如何将中间件与express.static一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆