我使用的是Windows7,我在全球安装了nodes 0.10.12和最新版本的express和express-generator。我
使用npm install创建了一个名为nodetest1的新express项目,并成功安装了所有依赖项。
转到http://localhost:3000/会渲染Express Welcome to Express -so it works。
我现在尝试使用节点并表示为简单的服务器,只使用一些html文件。
根据Don Nguyen所著的"Jump Start Node.js“一书,版权所有©2012 SitePoint Pty。Ltd.第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吗?我将在哪里添加新文件,在哪个文件夹中?
提前感谢
发布于 2014-08-28 02:03:19
快递应用是你开发的吗?
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
这将提供您放置在公共目录中的所有文件:
app.use(express.static(__dirname + '/public'));目录结构:
|-app.js
|-public
| |-index.html
| |-form.htmlYou‘s form.html will to to localhost:3000/form.html
如果您不想在没有扩展名的情况下提供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'));之前
注:您提到的这本书是2012年12月2日出版的。据github称,Express 3已于2013年10月23日发布。当前版本为4.8.5。您可能希望使用更新的参考资料。
https://stackoverflow.com/questions/25533983
复制相似问题