2014-08-27 34 views
0

我使用的是Windows 7.我在全局安裝了節點0.10.12和最新版本的express和express-generator。 I無法設置節點並將其表示爲服務文件

創建了一個名爲nodetest1的新快速項目,並使用npm install成功安裝了所有依賴關係。

http://localhost:3000/呈現Express Welcome to Express - 所以它的工作原理。

我嘗試使用節點並表示爲簡單的服務器現在只使用一些html文件。

根據這本書 「跳躍開始Node.js的」 唐阮©2012 SitePoint Pty有限公司[頁9-11],我編輯

app.js文件,並添加

var fs = require('fs'); 

var routes = require('./routes/index'); 
var users = require('./routes/users'); 

我加

app.get('/form', function(req, res) { 
    fs.readFile('./form.html', function(error, content) { 
    if (error) { 
     res.writeHead(500); 
     res.end(); 
    } else { 
     res.writeHead(200, { 'Content-Type': 'text/html' }); 
     res.end(content, 'utf-8'); 
    } 
    }); 
}); 

然後,我創建了一個簡單form.html文件,把它放在nodetest1目錄下,重新啓動我的服務器,並在命令行中,我得到

app.get('/form', function(req, res) { 
TypeError : Cannot call method 'get' of undefined 
npm ERR! weird error 8 
npm ERR! not ok code 0 

我在做什麼錯?我只想使用簡單的html,而不是Jade。

我也必須編輯我添加的每個html文件的app.js?我將在哪裏添加新文件,在哪個文件夾中?

在此先感謝

回答

1

您是否創建了快速應用程序?

var express = require('express'); 
var app = express(); 

此外,您可以使用res.sendFile爲此。

app.get('/form', function(req, res) { 
    return res.sendFile('form.html'); 
}); 

如果您服務了很多你可能想看看express.static中間件靜態文件。 http://expressjs.com/4x/api.html#app.use

這將成爲了你把你的公共目錄中的所有文件:你form.html將送達至localhost:3000/form.html

|-app.js 
|-public 
| |-index.html 
| |-form.html 

app.use(express.static(__dirname + '/public')); 

目錄結構

如果你不想在沒有擴展名的情況下提供html文件可以通過@robertklep使用其他答案中找到的解決方案來解決不同的問題。 Any way to serve static html files from express without the extension?

app.use(function(req, res, next) { 
    if (req.path.indexOf('.') === -1) { 
    var file = publicdir + req.path + '.html'; 
    fs.exists(file, function(exists) { 
     if (exists) 
     req.url += '.html'; 
     next(); 
    }); 
    } else { 
    next(); 
    } 
}); 

你會想這是以前app.use(express.static(__dirname + 'public'));


注意:你所提到的這本書出版12月2日,2012年3特快根據github上公佈的2013年10月23日。目前的版本是4.8.5。您可能想要使用更新的參考。

+0

'var express = require('express'); var app = express(); app.use(express.static(path.join(__ dirname,'public')));'在'app.js'中。我把'form.html'放在'public' dir和'http:// localhost:3000/form.html'中。謝謝! - 正常情況下,我把'http:// localhost:3000/form(最後沒有'.html'),並且不能正常工作並呈現'Error 404'? - 這是一個完整的服務器?因爲我提到的書建議編輯'app.js'和這個[tutorial](http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/),在第2部分中建議編輯路由和視圖。他們爲什麼不能使用'public' dir? – slevin 2014-08-27 18:48:20

+1

我在答案中添加了一些中間件,您可以使用它來實現此目的。它來自另一個答案在這裏:http://stackoverflow.com/questions/16895047/any-way-to-serve-static-html-files-from-express-without-the-extension – Jordonias 2014-08-27 18:55:10

相關問題