简体   繁体   中英

EJS and Express, can't figure how to load static files from root path

This question is mostly related to my setup so please bear with me as I try to explain it.

My folder structure looks like this:

.
├── server/
│   └── index.ts // the file that starts my server
├── pages/
│   └── index.ts // Generates index page
└── views/
    └── index.ejs // An ejs view
└── js/
    └── index.js // A simple js file with a console log in it

I'm starting an Express server from server/index.ts which looks for files inside the pages directory.

import * as express from "express";

const app = express();

app
  .set("view engine", "ejs")
  .get("*", function handler(req, res) {
    const _found = require(`${process.cwd()}/pages${req.url}`);
    res.render(_found.default(), {});
  })
  .listen(3000, () => console.log("Started on http://localhost:3000"));

My page files are fairly simple, they look like this:

function Index(): string {
  return `index.ejs`;
}

export default Index;

I use these files to tell my server which ejs template to use for that specific page. In the above case I return index.ejs , which tells my server to find views/index.ejs .

This works great, at least until I try to include any static files within my ejs templates.

<html>
  <body>
    <script src="/js/index.js"></script>
    <h1><%= pageName %></h1>
  </body>
</html>

For whatever reason, if I load this ejs template the way explained above, the server will try to look for /js/index.js inside pages/js/index.js rather than /js/index.js .

I've tried using a relative path:

<script src="../js/index.js"></script>

But this didn't work.

I can't put my static files inside the pages directory as that will break the way my server works.

How can I stop express from looking for files inside the wrong folder?

Express can apparently set a static folder, so I changed my server to:

app
  .set("view engine", "ejs")
  .use("/public", express.static("public"))
  .get("*", function handler(req, res) {
    const _found = require(`${process.cwd()}/pages${req.url}`);
    res.render(_found.default(), {});
  })
  .listen(3000, () => console.log("Started on http://localhost:3000"));

I then moved my static files to public/js/index.js and loaded them with <script src="/public/js/index.js"></script> .

This works as it should!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM