2015-05-17 36 views
0

首先讓我解釋一下,我不期望自己提交這個,因爲我曾多次嘗試過無數次的嘗試,但仍無法獲得通過expressjs提供的javascript和圖像。該項目的文件夾結構:javascript not loading使用快速靜態

[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); 

[USER1:./js/routes/user1]

[js] 
|routes  
    |user1.js 

代碼:

router.get('/', function(req, resp) { 
    resp.render("srcEvent1"); 
} 

[html:srcEvent.html]帶基本功能的e ASY讀數:

<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 &張圖片)

srcEvent.js在服務器上運行

function srcEvent_alert(){ 
    alert('srcEvent_alert:0006:'); 
} 

確定期望的連接。

瀏覽器的URL [本地主機:65000/USER1]

result1: without <script src="srcEvent.js"></script> page loaded :-) 
result2: with <script src="srcEvent.js"></script> page could not load :-(((

,讓我度過了交叉項目時間表,在幾天的實驗,從計算器WRT回答了許多緊張無數的時間和其他地方,而只是我的沒有,雖然設置工作似乎符合那些Google搜索引用。

有人請幫我拿出那個地牢。

謝謝。

丹尼爾

+0

爲什麼要通過相對路徑而不是使用它的package.json中配置的入口點來使用npm模塊?例如,「var express = require(」express「);」 – bitifet

回答

0

也許你正在使用相對路徑(沒有斜線)<script src="srcEvent.js">所以它會試圖在/staticFiles/user/srcEvent.js儘量找JS將其更改爲<script src="/srcEvent.js">,看看它是否工作。

此外,我會建議你使用developer tools在瀏覽器內部,看看哪些網址完全相同它會嘗試加載(從網絡面板)

附:您可以使用require('express')而不是require('./node_modules/express/lib/express'),因爲節點本身查找node_modules文件夾內的依賴關係

+0

我已經按照其中幾個顯示的那樣做了,但每次只顯示一個: < SCRIPT SRC = 「./ srcEvent.js 」>

+0

與Firefox dev的控制檯網絡我看到:GET srcEvent.js localhost:65000&GET user1 localhost:65000 –

+0

我根據你的建議改爲require('express')重新運行服務器,但是當使用中的瀏覽器沙球不停地旋轉時,srcEvent.js。 –