Node.js 让ExpressJS为映射路径返回404
因此,我的ExpressJS应用程序具有以下开发配置:Node.js 让ExpressJS为映射路径返回404,node.js,express,Node.js,Express,因此,我的ExpressJS应用程序具有以下开发配置: //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
//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(uu dirname+'/components')代码>但是,如果我尝试加载一个带有/components路径的文件,但该文件不存在,那么它正在加载index-dev.html,我希望在其中出现404错误。有没有办法修改:
app.get('*', function(req, res) {
res.sendfile("index-dev.html");
});
因此,对于已设置但找不到文件的静态路径,它将返回404,如果路径不是静态路径之一,则返回index-dev.html?如果在/components
中查询不存在的文件,Express将继续在路由链中匹配。您只需添加以下内容:
app.get('/components/*', function (req, res) {
res.send(404);
});
只有对不存在的静态文件的请求才会与此路由匹配。当请求为静态文件时,您可以对其进行修改,以防止提供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/
开头的路径提供index-dev.html
。
对于这些路径,请求将被传递到下一个处理程序,由于找不到任何处理程序,因此将导致404