让ExpressJS为映射path返回404

所以我有我的ExpressJS应用程序的以下开发configuration:

//core libraries var express = require('express'); var http = require('http'); var path = require('path'); var connect = require('connect'); var app = express(); //this route will serve as the data API (whether it is the API itself or a proxy to one) var api = require('./routes/api'); //express configuration app.set('port', process.env.PORT || 3000); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); app.use(connect.compress()); //setup url mappings app.use('/components', express.static(__dirname + '/components')); app.use('/app', express.static(__dirname + '/app')); app.use(app.router); require('./api-setup.js').setup(app, api); app.get('*', function(req, res) { res.sendfile("index-dev.html"); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); 

现在你可以看到我正在做app.use('/components', express.static(__dirname + '/components')); 但是如果我尝试加载一个带有/ componentspath的文件并且它不存在,那么它会加载index-dev.html,我想要一个404错误。 有什么办法可以修改:

 app.get('*', function(req, res) { res.sendfile("index-dev.html"); }); 

所以它会返回一个404的静态path设置,但无法find该文件,并返回索引dev.html如果path不是静态path之一?

如果您查询/components中不存在的文件,Express将在路由链中继续匹配。 你只需要添加这个:

 app.get('/components/*', function (req, res) { res.send(404); }); 

只有不存在的静态文件的请求才会匹配这条path。

您可以对其进行修改,以防止在请求针对静态文件时提供index-dev.html

 app.get('*', function(req, res, next) { // if path begins with /app/ or /components/ do not serve index-dev.html if (/^\/(components|app)\//.test(req.url)) return next(); res.sendfile("index-dev.html"); }); 

这样它将不会为/components//app/开头的path提供index-dev.html 。 对于这些path,请求将被传递到下一个处理程序,并且因为没有find,它将导致404