0

Apologies for this question which may be seen as basic but I feel there must be an easy method for this for such a popular framework yet I am struggling to come across it.

I am wanting to serve page routes using a relative path. i.e. sendFile("/pages/index.html") but the only solution that works is using sendFile(__dirname + "/pages/index.html")

I have read posts which say to add app.use(express.static("public")) to serve static content but this only impacts get requests to the full URL from client not the sendFile() from server.

i.e. If client types http://...../pages/index.html it correctly returns but when they type http://...../ and I use sendFile("/pages/index.html") the route is incorrect.

Relevant chunks of code are below

const express = require('express');
const app = express();

app.use(express.urlencoded({extended: false}))
app.use(express.static("public"))

app.get("/", (req, res) => {
    res.status(200);
    res.sendFile("/pages/index.html")
});

Directory structure is public, public/css, public/js, public/pages.

Again all I'm trying to do is not have to write __dirname in every sendFile(). I feel like I'm missing something. Any suggestions are appreciated :) Thanks

jacktim
  • 420
  • 4
  • 11

1 Answers1

0

As @Yasio linked https://stackoverflow.com/a/52031283/9488284 (Thank You). The solution is to create a middleware function that prepends __dirname to every sendFile and then use that function instead of sendFile.

Like such

app.use((req, res, next) => {
  res.show = (name) => {
    res.sendFile(`/public/${name}`, {root: __dirname});
  };
  next();
});

You can then display pages (in my dir structure) using

app.get('/demo', (req, res) => {
  res.show("pages/index.html");
});

i.e. when someone requests http://.../ you will return to them pages/index.html. This essentially means instead of using sendFile() use show() to return files.

jacktim
  • 420
  • 4
  • 11