Node.js EJS和Express,can';t了解如何从根路径加载静态文件
这个问题主要与我的设置有关,所以请耐心听我解释 我的文件夹结构如下所示:Node.js EJS和Express,can';t了解如何从根路径加载静态文件,node.js,express,ejs,Node.js,Express,Ejs,这个问题主要与我的设置有关,所以请耐心听我解释 我的文件夹结构如下所示: . ├── 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
.
├── 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
function Index(): string {
return `index.ejs`;
}
export default Index;
我正在从server/index.ts
启动一个Express server,它在页面
目录中查找文件
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"));
我的页面文件相当简单,如下所示:
.
├── 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
function Index(): string {
return `index.ejs`;
}
export default Index;
我使用这些文件告诉我的服务器该特定页面使用哪个ejs模板。在上面的例子中,我返回index.ejs
,它告诉我的服务器查找视图/index.ejs
这非常有效,至少在我尝试在ejs模板中包含任何静态文件之前是如此
<html>
<body>
<script src="/js/index.js"></script>
<h1><%= pageName %></h1>
</body>
</html>
但这不起作用
我不能将静态文件放在页面
目录中,因为这样会破坏服务器的工作方式
如何阻止express在错误的文件夹中查找文件?express显然可以设置静态文件夹,因此我将服务器更改为:
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"));
然后,我将静态文件移动到public/js/index.js
,并用
加载它们
这是它应该做的