我使用的是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
?我將在哪裏添加新文件,在哪個文件夾中?
在此先感謝
'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
我在答案中添加了一些中間件,您可以使用它來實現此目的。它來自另一個答案在這裏:http://stackoverflow.com/questions/16895047/any-way-to-serve-static-html-files-from-express-without-the-extension – Jordonias 2014-08-27 18:55:10