Home > Software engineering >  Why does my NodeJS Express app serve the entire website when sendFile() only contains path to one pa
Why does my NodeJS Express app serve the entire website when sendFile() only contains path to one pa

Time:10-21

my directories are as follows

//SE-Metro-Q
...<other files>
...contact.html
//SE-Metro-Q-Private
...server.js

Each directory is a separate set of webpages in their own website, and from a webpage in SE-Metro-Q-Private, I am redirecting to a webpage in SE-Metro-Q in a get request.

I have the following middleware:

app.use("/contactForm", express.static(path.join(__dirname, '/../SE-Metro-Q')));

And then the route:

app.get('/contactForm', (req, res) => {
    res.sendFile('contact.html', { root: path.join(__dirname, '/../SE-Metro-Q') });
})

From what I understand when I go to /contactForm on the browser, it should only load contact.html, but instead it loads index.html from the SE-Metro-Q directory specified in the middleware above.

How can I modify it to only load contact.html?

CodePudding user response:

express.static() serves a directory of static files; you've mounted your local path /../SE-Metro-Q to the /contactForm route. As such, Express will serve the entire directory off the /contactForm route.

If you want to only serve one file, remove your express.static() route entirely and explicitly respond with the file you want to serve on that route, just as you have in your second snippet.

  • Related