[英]How to use external javascript file into an ejs file
我在一個新的門戶網站工作。 到目前為止,使用 express 和 node.js 我有一個服務器和一些 ejs 文件。
我網站的主體結構是這樣的:
- node modules
- public
--javascript
---myScript.js
-views
--pages
---index.ejs
---about.ejs
--partials
---footer.ejs
---head.ejs
---header.ejs
package.json
server.js
服務器.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs'); // set the view engine to ejs
app.get('/', function(req, res) {res.render('pages/index');}); // index page
app.get('/about', function(req, res) { res.render('pages/about');}); // about page
app.listen(8080);
console.log('Portal is listening to port 8080 ');
和 index.ejs
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">
<header>
<% include ../partials/header %>
</header>
<main>
<div class="jumbotron">
<h1>MyPortal</h1>
<button>Press</button>
<% var test = 101; %>
</div>
</main>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
在部分中,我想調用並使用外部 .js 文件/public/javascript/myScript.js
以便我可以在我的 ejs 頁面中使用它的變量或發送一個變量。
我的 js 文件有一個簡單的函數(只是為了看看它是否工作),如果按下按鈕(在 index.ejs 中),它會在控制台中打印。
我的腳本.js
$(function() {
$("button").on("click", function () {
console.log("button pressed");
});
});
我正在嘗試在 head.ejs (或在 index.ejs )中調用外部js...
<!-- views/partials/head.ejs -->
<meta charset="UTF-8">
<title>MyPortal</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>body { padding-top:50px; } </style>
<script type="text/javascript" src="/pubic/javascript/myScript.js"></script>
但我收到此錯誤(在控制台中)
Loading failed for the <script> with source “http://localhost:8080/pubic/javascript/myScript.js”.
知道為什么會發生這種情況以及如何解決嗎?
由於您正在嘗試加載客戶端JavaScript,因此您使用 EJS 的事實無關緊要。 模板中只需要一個標准的 HTML 腳本元素,而您已經擁有了。
但是,您確實需要提供一個 URL(帶有 src 屬性),Web 瀏覽器可以使用該 URL 來獲取腳本……而您的腳本沒有 URL。
您收到消息Loading failed for the source “http://localhost:8080/pubic/javascript/myScript.js”.
因為這是一個 404 錯誤。
您應該使用靜態模塊為 JS 文件提供 URL。
app.use("/public", express.static('public'))
將此添加到您的 server.js 文件 app.use(express.static(__dirname + "/public");
並將 js 文件與您的 ejs 文件鏈接起來,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.