2013-10-06 4 views
2

그래서이 내 ExpressJS 응용 프로그램에 대해 다음 dev에 설정 : 이제얻기 ExpressJS 매핑 경로 (404)를 반환하는

//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')); 그러나 내가 가진 파일을로드하려고하면/components 경로이고 존재하지 않으면 index-dev.html을로드하고 404 오류가 발생합니다.

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

을 따라서 경로가 정적이 아닌 경우는 설정하지만 파일을 찾아 인덱스 dev.html을 반환 할 수 없습니다 정적 경로에 대한 404을 반환 할 것 : 수정하는 방법이 있나요 경로?

답변

3

존재하지 않는 /components의 파일을 쿼리하면 Express는 경로 체인에서 계속 일치합니다. 다음을 추가하기 만하면됩니다.

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

존재하지 않는 정적 파일에 대한 요청 만이 경로와 일치합니다.

0

는 요청이 정적 파일을 때 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이됩니다.

관련 문제