Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 让ExpressJS为映射路径返回404_Node.js_Express - Fatal编程技术网

Node.js 让ExpressJS为映射路径返回404

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

因此,我的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 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