【发布时间】:2019-08-14 19:21:39
【问题描述】:
我在一个新的门户网站工作。到目前为止,使用 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
server.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 中),它会在控制台中打印。
myScript.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”.
知道为什么会发生这种情况以及如何解决吗?
【问题讨论】:
-
public输入错误pubic -
是的,我只是展示它...我将其更改为“公共”,但问题仍然存在
-
你能在浏览器中打开脚本的 url 看看它是否显示什么吗?
-
type="text/javascript"不应在 HTML 5 中使用。它除了允许您打错字和破坏脚本之外没有其他用途。 -
niko 在设置视图引擎后尝试添加这个
app.use(express.static(path.join(__dirname, 'public')));。您还需要要求路径模块var path = require('path');
标签: javascript node.js express ejs