2015-12-21 77 views
2

我正在學習Mean.js堆棧,並嘗試構建應用程序。我已經安裝了Express,並且它可以工作。當我試圖配置我的靜態文件(html,js,圖像等)時,事情就破裂了。無法獲取/快速錯誤

這裏是我的文件:

server.js

var express = require('express'); 
var app = express(); 
app.use(express.static(__dirname + "public")); 

app.listen(3000); 
console.log('Server running on port 3000'); 

我的HTML文件很簡單:

<!DOCTYPE> 
<html> 
<head> 
    <title>Contact List App</title> 
</head> 
<body> 
    <h1>Contact List App</h1> 
</body> 
</html> 

所以,當我啓動服務器:node server.js,然後我在瀏覽器中輸入http://localhost:3000/,出現「無法獲取」錯誤。

問題在哪裏?

enter image description here

回答

0

__dirname沒有結尾的斜線,所以你需要提供一個自己建立的靜態根時:

app.use(express.static(__dirname + "/public")); 
            ^this needs to be there 
0

你需要確保的路徑存在。此外,使用路徑加入字符串是一種更好的做法。另外,請確保目錄public存在,並且文件index.html位於該文件夾內。

var path = require('path'); 
var express = require('express'); 
var app = express(); 
app.use(express.static(path.join(__dirname, 'public'))); 

app.get('/', function(req, res){ 
    res.render('index.html'); 
}); 

app.listen(3000); 
console.log('Server running on port 3000');