Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ExpressJS to return 404 for mapped path

So I have the following dev config for my ExpressJS application:

//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'));
});

Now you can see that I am doing app.use('/components', express.static(__dirname + '/components')); however if I try to load a file with the /components path and it does not exist, it is loading the index-dev.html where I would want a 404 error. Is there any way to modify:

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

So that it will return a 404 for static paths that are setup but can't find the file and return index-dev.html if the path is not one of the static paths?

like image 313
ryanzec Avatar asked Feb 28 '26 22:02

ryanzec


1 Answers

If you query a file in /components that does not exist, Express will continue matching in the route chain. You just need to add this:

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

Only requests for static files that does not exist will match this route.

like image 138
Laurent Perrin Avatar answered Mar 03 '26 12:03

Laurent Perrin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!