javascript - 无法设置 Node 和express来提供文件

标签 javascript node.js express

我使用Windows 7。我在全局安装了 Node 0.10.12以及最新版本的express和express-generator。我

创建了一个名为 nodetest1 的新 Express 项目并使用 npm install 成功安装了所有依赖项。

前往http://localhost:3000/渲染Express Welcome to Express -这样就可以了。

我现在尝试使用node和express作为简单的服务器,只需使用一些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。

我还必须编辑 app.js对于我添加的每个 html 文件?我将在哪里添加新文件,在哪个文件夹中?

提前致谢

最佳答案

您是否创建了 Express 应用程序?

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

这将提供您放入公共(public)目录中的所有文件:

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

目录结构:

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

您的form.html将被提供给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。您可能想使用更新的引用。

关于javascript - 无法设置 Node 和express来提供文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25533983/

相关文章:

node.js - Graphql Dataloader 文件结构和上下文

javascript - SSE 服务器在几次尝试后停止响应

mysql - 每次我登录时,总是出现 CANNOT POST/login

javascript - 表达 res.redirect 导致 "Uncaught SyntaxError: Unexpected token <"

javascript - Google Analytics AJAX 电子商务跟踪

javascript - 如何对div数据进行降序排序

javascript - Bootstrap 幻灯片事件在 AJAX 成功中不起作用

node.js - 适用于 NodeJs 的 Azure 通知中心(注册更新并替换标签)

javascript - 使变量可供其他 Node 模块访问

javascript - Node.js http-proxy 丢弃 websocket 请求