简体   繁体   中英

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

I'm running a NodeJS server with Express, using Handlebars as the engine.

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.");
});

I have a login page:

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();
});

– which is using this 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>

– but I cannot use any of the functions from in login.js .

I also got some "MIME type (“text/html”) mismatch" errors, but I think I fixed them by using

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

– but I still can't use any of the functions. I also tried multiple browsers, but nothing worked.

Let app.use(express.static(publicDirPath)) play it's role. Move local js/css file under publicDirPath dir, the express will serve assets' path for you.

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