Ben Alan
Ben Alan

Reputation: 1695

node's get() function is never called when serving static files

When I go to localhost:3000, app.get() is not called.

const express = require('express');
const app = express();
app.use(express.static('public'));

app.get('/', (req, res) => {
  console.log("What's up")
});

app.listen(3000, () => console.log('listening at 3000'));

Besides the index, it seems that no pages call the function.

The only thing that fixes it is if I turn off app.use(express.static('public')); But then I can't access my page.

What am I supposed to do to get get() working with a /public folder?

Upvotes: 0

Views: 135

Answers (2)

Ben Alan
Ben Alan

Reputation: 1695

In light of jfriend00's answer it seems I can't do this. Fortunately, my application doesn't need a get request on the homepage so I set up a views page with the view engine 'pug.' This solved the problem of having "no pages" able to respond to get requests, but if you need to make a get request on a homepage set by express.static() I guess your out of luck?

const express = require('express');
const app = express();
const path = require('path')
var pug = require('pug');
app.use(express.static('public'));
app.set('views', path.join(__dirname, 'views'))
app.set('view engine','pug');
app.get('/hidden', async (req, res) => {
  console.log("What's up");
  res.render('hidden');
});

app.listen(3000, () => console.log('listening at 3000'));

So as long as I have a views/hidden.pug in the root folder I can make a get request to it. This works for me, but perhaps there are other more valid solutions.

Upvotes: 0

jfriend00
jfriend00

Reputation: 708016

If express.static() finds a match for the incoming URL, then it handles the request and nothing else gets a chance. So, you should only be defining routes that don't match filenames in the public folder. Or, you should only be putting files in the public folder that you want express.static() to match and handle the entire request.

You get one or the other, not both. Either express.static() finds a match and handles the request or it doesn't find a match and your other routes get a chance to match it.

Upvotes: 1

Related Questions