How to prevent express server from serving api routes from the static folder

Viewed 2278

Hi I need some help with how express handles routes.

In setting up my express app, I have something like this: app.use(express.static('public'));

Next, I mount some api routes:

app.use('/api', myrouter);
app.get('*', function(req, res) {
    res.sendFile(path.resolve('public/index.html'));
});

But, when the frontend requests data via an api route, e.g. at 'localhost:3000/api/things', I am seeing in the Express debug logs that at some point (unsure when) it actually tries to serve this request as a static file, like:

send stat "C:\myproject\public\api\things" +230ms

Even though this folder doesn't exist in 'public' and should be solely handled by my api. FYI, the handler for /api/things route is only implemented for the GET method, and does get invoked at some point.

How do I stop express server from also trying to serve api requests from the static folder?

Thanks very much.

2 Answers

Your answer is misinformed, or rather you've misinterpreted the problem. Your original configuration:

app.use(express.static(__dirname + 'public'));
app.use('/api', myrouter);

Looks absolutely fine because there's no clash between the routes. The threads you've linked too aren't really the same, and I can see why moving the routes in those cases would have worked.

The only thing I'd say is your path to your static folder isn't reliable, you should really use path.join, or actually in your case you can just do express.static('public') - express will infer the folder your app is served from.

Related