【发布时间】:2015-05-17 08:48:13
【问题描述】:
首先让我解释一下,我不希望自己提交这个,因为我已经提到并反复尝试了无数次尝试,但我仍然无法获得通过 expressjs 提供的 javascript 和图像。项目文件夹结构:
[root] (the project folder)
|server.js <-- the main file
|[staticFiles] (contains js img files)
|[html] (contains html files)
|[js] (contains javascripts)
|[node_modules] (library home)
server.js:(主文件)
var express = require('lib/express');
var app = express();
var port = process.env.PORT || 65000;
var bodyParser = require('./node_modules/body-parser');
var router = express.Router();
var cons = require('consolidate');
var path = require('path');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', "./html");
app.use('/user1', require('./js/routes/user1'));
// here i'd tried various combinations:
var staticPathFinal = express.static(path.join(__dirname, 'staticFiles'));
app.use(staticPathFinal);
// app.use(express.static(path.join(__dirname, 'staticFiles')));
// app.use(express.static(__dirname, 'staticFiles'));
// app.use(express.static(__dirname + '/staticFiles'));
// app.use(express.static(__dirname + '/staticFiles/')); // 2123
// app.use(express.static('staticFiles')); // 2159
// app.use('/user', express.static('staticFiles'));
// app.use('/user', express.static(path.join(__dirname, 'staticFiles')));
app.listen(port);
[用户1:./js/routes/user1]
[js]
|routes
|user1.js
代码:
router.get('/', function(req, resp) {
resp.render("srcEvent1");
}
[html: srcEvent.html] 删除了基本内容以便于阅读:
<head lang="en">
<title>srcEvent.html</title>
<script src="srcEvent.js"></script>
</head>
<body onload="srcEvent_alert()">
<h1>page info: this shall activate alert from srcEvent.js:</h1>
</body>
[staticFiles](包含 javascript 和 img 的文件夹)
srcEvent.js
function srcEvent_alert(){
alert('srcEvent_alert:0006:');
}
在服务器上运行正常预期连接。
在浏览器 url [localhost:65000/user1]
result1: without <script src="srcEvent.js"></script> page loaded :-)
result2: with <script src="srcEvent.js"></script> page could not load :-(((
这让我花了几天时间跨越项目时间线来尝试来自 stackoverflow 和其他地方的答案,但我的工作似乎没有用,尽管设置似乎符合那些谷歌搜索的参考。
请有人帮我走出那个地牢。
谢谢。
丹尼尔
【问题讨论】:
-
为什么你需要通过相对路径的 npm 模块,而不是使用 package.json 中配置的入口点?例如,«var express = require("express");»
标签: javascript express static onload src