ExpressJS,用于在GET请求上呈现内容



我有一个html页面,如下所示

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Report</title>
<link rel="stylesheet" href="assets/app.css"/></head><body>
//Content//
<div id="report"></div><script src="assets/app.js"></script></body></html>

此 html 页面位于具有结构的文件夹下方

report
--assets
--app.js
--app.css
--myfile.html

现在我有我的应用程序,它正在尝试呈现这个 html。以下是位于路线中.js结构

如下
app.use('/Users/report/assets', express.static('/Users/report/assets'));
app.get('/api/testresults/:id', (req, res) => {
const id = req.params.id;
res.sendFile('/Users/report/myfile.html');
});

我的应用程序结构如下

MyApp 
app 
—routes
—index.js
—routes.js
node_modules
package.json
server.js

我应该在这里添加什么。我不想更改 html,因为我相信一旦我使用 express.static(( 它应该能够找到文件 我不断收到错误应用程序.js找不到 404

注意:如果我将我的 html 的 href 更改为

/Users/report/assets/app.js 

CSS也是如此,它可以工作,但我不希望那样。

如果您希望资源(如assets/app.css(独立于它们来自的页面的 URL,以便它们可以位于文件系统中的任何位置,请停止使用相对 URL。 使用绝对 URL 在网页中引用它们,例如:

/assets/app.css
/assets/app.js

然后,您可以非常轻松地配置express.static()路由来处理所有页面的它们。

app.use(express.static("put directory here that contains the assets folder"));

我从你的问题中推断出

app.use(express.static('/Users/report'));

当 Express 收到/assets/app.css请求时,它将检查express.static()路由处理程序。 如果您在express.static()中为assets文件夹指定了父目录,则该路由处理程序将在该目录中查找您想要/assets/app.css

因此,在上面的示例中,它将接受/assets/app.css的请求并将其与express.static('/Users/report')中指定的路径合并并查看:

/Users/report/assets/app.css

这将是你想要的。

当您在 HTML

文件中的资源上使用的路径不以http:///开头时,浏览器会将其视为相对于页面的 URL,因此浏览器采用网页的路径并将其预置到 HTML 中指定的 URL。 这确实使静态资源复杂化,因此通常不是您想要的。 相反,您希望通过确保它们以/开头来使它们成为绝对路径。 然后,它们很容易设置路由,因为无论包含它们的页面的路径是什么,路由都是相同的。

您仍在尝试引用路径/Users/report/assetshtml 中的位置<script src="assets/app.js"></script>

尝试更改以下代码,

app.use('/Users/report/assets', express.static('/Users/report/assets'));

app.use('assets', express.static('/Users/report/assets'));

因为你有:

app.use('/Users/report/assets', express.static('/Users/report/assets'));

无论哪种方式.js都应将应用用作路径应用.js而不是资产/应用.css

最新更新