nodejs&强大的标题错误

时间:2012-02-05 00:30:48

标签: node.js formidable

继续:The Node Beginner Book

我无法调试此问题或在线查找解决方案。 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);

router.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;

server.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 个答案:

答案 0 :(得分: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);

        ...

答案 1 :(得分:0)

上述代码对我来说是值得的。

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

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

在我看来,强大的应该检查参数是否存在(typeof(this.headers['content-length']) != undefined)。如果您确定了您尝试上传的浏览器和文件类型,那么它会对其他人有帮助,那么您可以在https://github.com/felixge/node-formidable/

提交错误信息

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

答案 2 :(得分: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

答案 3 :(得分: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);
...
}
}

希望你解决问题