10

跟随:节点初学者书

我无法调试此问题或在线找到解决方案。Node.js 的新手,希望有人能提供解决方案

错误:已更新控制台日志信息 2012 年 2 月 11 日星期六上午 7:27:17

Request for/ received!
About to route a request for /
Request handler 'start' was called.
Request for/favicon.ico received!
About to route a request for /favicon.ico
No request handler found for /favicon.ico
Request for/favicon.ico received!
About to route a request for /favicon.ico
No request handler found for /favicon.ico
Request for/upload received!
About to route a request for /upload
Request handler 'upload' was called.
about to parse
{ output: [],
  outputEncodings: [],
  writable: true,
  _last: false,
  chunkedEncoding: false,
  shouldKeepAlive: true,
  useChunkedEncodingByDefault: true,
  _hasBody: true,
  _trailer: '',
  finished: false,
  socket: 
   { _handle: 
      { writeQueueSize: 0,
        socket: [Circular],
        onread: [Function: onread] },
     _pendingWriteReqs: 0,
     _flags: 0,
     _connectQueueSize: 0,
     destroyed: false,
     bytesRead: 66509,
     bytesWritten: 638,
     allowHalfOpen: true,
     writable: true,
     readable: true,
     server: 
      { connections: 1,
        allowHalfOpen: true,
        _handle: [Object],
        _events: [Object],
        httpAllowHalfOpen: false },
     ondrain: [Function],
     _idleTimeout: 120000,
     _idleNext: 
      { _idleNext: [Circular],
        _idlePrev: [Circular],
        ontimeout: [Function] },
     _idlePrev: 
      { _idleNext: [Circular],
        _idlePrev: [Circular],
        ontimeout: [Function] },
     _idleStart: Sat, 11 Feb 2012 15:25:28 GMT,
     _events: { timeout: [Function], error: [Function], close: [Object] },
     ondata: [Function],
     onend: [Function],
     _httpMessage: [Circular] },
  connection: 
   { _handle: 
      { writeQueueSize: 0,
        socket: [Circular],
        onread: [Function: onread] },
     _pendingWriteReqs: 0,
     _flags: 0,
     _connectQueueSize: 0,
     destroyed: false,
     bytesRead: 66509,
     bytesWritten: 638,
     allowHalfOpen: true,
     writable: true,
     readable: true,
     server: 
      { connections: 1,
        allowHalfOpen: true,
        _handle: [Object],
        _events: [Object],
        httpAllowHalfOpen: false },
     ondrain: [Function],
     _idleTimeout: 120000,
     _idleNext: 
      { _idleNext: [Circular],
        _idlePrev: [Circular],
        ontimeout: [Function] },
     _idlePrev: 
      { _idleNext: [Circular],
        _idlePrev: [Circular],
        ontimeout: [Function] },
     _idleStart: Sat, 11 Feb 2012 15:25:28 GMT,
     _events: { timeout: [Function], error: [Function], close: [Object] },
     ondata: [Function],
     onend: [Function],
     _httpMessage: [Circular] },
  _events: { finish: [Function] } }

/usr/local/lib/node_modules/formidable/lib/incoming_form.js:247

undefined
  if (this.headers['content-length']) {
                  ^

TypeError: Cannot read property 'content-length' of undefined
    at IncomingForm._parseContentLength (/usr/local/lib/node_modules/formidable/lib/incoming_form.js:247:19)
    at IncomingForm.writeHeaders (/usr/local/lib/node_modules/formidable/lib/incoming_form.js:126:8)
    at IncomingForm.parse (/usr/local/lib/node_modules/formidable/lib/incoming_form.js:80:8)
    at Object.upload [as /upload] (/Applications/MAMP/htdocs3/js/nodejs/webapp/requestHandlers.js:34:8)
    at route (/Applications/MAMP/htdocs3/js/nodejs/webapp/router.js:4:20)
    at Server.onRequest (/Applications/MAMP/htdocs3/js/nodejs/webapp/server.js:20:3)
    at Server.emit (events.js:70:17)
    at HTTPParser.onIncoming (http.js:1511:12)
    at HTTPParser.onHeadersComplete (http.js:102:31)
    at Socket.ondata (http.js:1407:22)

结束错误

requestHandlers.js

var querystring = require("querystring"),
    fs = require("fs"),
    formidable = require("formidable");

function start(response) {
  console.log("Request handler 'start' was called.");

  var body = '<html>'+
    '<head>'+
    '<meta http-equiv="Content-Type" '+
    'content="text/html; charset=UTF-8" />'+
    '</head>'+
    '<body>'+
    '<form action="/upload" enctype="multipart/form-data" '+
    'method="post">'+
    '<input type="file" name="upload" multiple="multiple">'+
    '<input type="submit" value="Upload file" />'+
    '</form>'+
    '</body>'+
    '</html>';

    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);
    response.end();
}

function upload(response, request) {
  console.log("Request handler 'upload' was called.");

  var form = new formidable.IncomingForm();
  console.log("about to parse");
  form.parse(request, function(error, fields, files) {
    console.log("parsing done");

    /*
     * Some systems [Windows] raise an error when you attempt to rename new file into one that already exists.
     * This call deletes the previous .PNG image prior to renaming the new one in its place.
    */
    fs.unlinkSync(__dirname +"/tmp/test.jpg");
    fs.renameSync(files.upload.path, "/tmp/test.jpg");
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("received image:<br/>");
    response.write("<img src='/show' />");
    response.end();
  });
}

function show(response) {
  console.log("Request handler 'show' was called.");
  fs.readFile(__dirname + "/tmp/test.jpg", "binary", function(error, file) {
    if(error) {
      response.writeHead(500, {"Content-Type": "text/plain"});
      response.write(error + "\n");
      response.end();
    } else {
      response.writeHead(200, {"Content-Type": "image/jpg"});
      response.write(file, "binary");
      response.end();
    }
  });
}

exports.start = start;
exports.upload = upload;
exports.show = show;

index.js

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/show"] = requestHandlers.show;

server.start(router.route, handle);

路由器.js

function route(handle, pathname, response, request) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
    handle[pathname](response, request);
  } else {
    console.log("No request handler found for " + pathname);
    response.writeHead(404, {"Content-Type": "text/html"});
    response.write("404 Not found");
    response.end();
  }
}

exports.route = route;

服务器.js

var http = require("http");
var url = require("url");

function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    route(handle, pathname, response, request);
  }

  // http.createServer(onRequest).listen(8888);
  //  console.log("Server has started.");
    http.createServer(onRequest).listen(1337, "127.0.0.1");
    console.log('Server Has Started!');
}

exports.start = start;
4

4 回答 4

2

无需使用旧版本的 Node 和 Formidable。我能够让该示例与 Node v0.10.20 和 Formidable v1.0.14 一起使用。看来该files.upload属性已不再使用。

只需从书中更改以下行:

    fs.rename(files.upload.path, "/tmp/test.png", function(error) { ... });

    fs.rename(files.file.path, "/tmp/test.png", function(error) { ... });

...然后上传完美!


该示例的另一个可选调整(尤其是对于 Windows 开发人员)

我没有使用错误状态fs.rename()来确定文件是否已经存在,而是很幸运地使用fs.exists()它来检查感觉不像黑客攻击的现有文件。我还将 test.png 文件保存到本地目录,因为这/tmp是一个非常不自然的 Windows 路径...

var img = "./test.png";

...

    fs.exists(img, function(exists){
        if(exists){ fs.unlink(img); }

        fs.rename(files.file.path, img);

        ...
于 2013-10-08T00:39:45.760 回答
0

对于它的价值,上面的代码对我有用。

问题似乎发生在强大的范围内。检查 node_modules 中的 package.json 我在node -v= v0.4.12 上使用版本 1.0.8。

您正在发出的浏览器或请求似乎在请求中不包含内容长度标头。我使用的是 Chrome,但如果您使用的是 CURL,或者可能以异步方式或作为流发出请求,则请求中可能没有导致此问题的 content-length 标头。这在这里有所讨论: https ://github.com/felixge/node-formidable/issues/93

在我看来,强大的应该正确检查参数的存在(typeof(this.headers['content-length']) != undefined)。如果您确定您的浏览器和您尝试上传的文件类型,这将对其他人有所帮助,然后您可以在https://github.com/felixge/node-formidable/提交错误

注意:您也可以将此问题的标题更新为nodejsnot nodjs。祝节点好运!

于 2012-02-12T15:57:15.000 回答
0

如果您使用与本教程中使用的相同版本的 Formidable 和 Node.js,则代码可以像宣传的那样工作。

教程中使用的 Formidable 版本是1.0.2。要获取此版本,请发出:

$ sudo npm install formidable@1.0.2

Node.js 的版本是0.6.10,可以在这里找到:https ://github.com/joyent/node/tags

于 2013-01-24T04:14:28.633 回答
0

好吧,我的代码与您相同,但在 RequestHandlers.js 上的函数上传稍有变化,请尝试更改此代码:

function upload(response, request) { 
...
var form = new formidable.IncomingForm();
...
}

对此:

function upload(response, request){
...
var form = new formidable.IncomingForm(), files = [], fields = [];
...
}

如果这不起作用,您应该能够看到请求标头是如何形成的:

function upload(response, request){
...
form.parse(request, function(error, fields,files){
console.dir(request.headers);
...
}
}

希望你解决你的问题

于 2014-04-28T04:58:28.950 回答