繁体   English   中英

如何在 Express 中将 JavaScript 文件链接到 HTML?

[英]How do I link a JavaScript file to HTML in Express?

我正在运行一个带有 Express 的 NodeJS 服务器,使用 Handlebars 作为引擎。

app.use(express.static(publicDirPath))
(...)

app.engine("hbs",hbs({
extname: "hbs",
defaultView: "main",
layoutsDir: path.join(srcDirPath, "views/layouts"),
partialsDir: path.join(srcDirPath, "views/partials"),
}));  
(...)

app.listen(3000, () => {
  console.log("Server started at port 3000.");
});

我有一个登录页面:

app.get("/Login", (req, res) => {
  res.render("Login", { layout: "Loginlayout" });
});

app.get("/public/js/login.js", (req, res) => {
  res.header("Content-Type", "application/javascript")
  res.end();
});

– 这是使用这个 header:

 <head>
    <script src="/public/js/login.js" async></script>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="css/login.css">

    <title>Login</title>
  </head>

– 但我不能使用login.js中的任何功能。

我也遇到了一些“MIME 类型(“text/html”)不匹配”错误,但我想我通过使用修复了它们

res.header("Content-Type", "application/javascript")

– 但我仍然无法使用任何功能。 我也尝试了多个浏览器,但没有任何效果。

app.use(express.static(publicDirPath))发挥它的作用。 将本地 js/css 文件移动到publicDirPath目录下,快递将为您提供资产的路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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