强大和 Node.js TypeError:无法读取未定义的属性“路径" [英] Formidable and Node.js TypeError: Cannot read property 'path' of undefined
问题描述
如果您正在阅读本文,您可能正在关注 Manuel Kiessling 的 Node 教程.我在完成教程的文件上传部分时收到以下错误.
If you're reading this, you're probably following Manuel Kiessling's Node tutorial. I was receiving the following error when completing the file upload part of the tutorial.
fs.rename(files.upload.path, "img/img.jpg", function(error) {
^
TypeError: Cannot read property 'path' of undefined
我四处搜索,发现这个和
I searched around, found this and this, but they were pretty inconclusive and provided little help.
推荐答案
首先,教程确实以错误的顺序传递请求和响应.我做的第一件事是将顺序从 (response, request)
更改为 (request, response)
.(确保在任何地方都这样做).这样做的原因是因为我非常确定 HTTP
的 createServer()
中的 onRequest
函数按此顺序传递它们.
First, it is true that the tutorial is passing request and response in the wrong order. The first thing I did is changed the order from (response, request)
to (request, response)
. (Make sure to do this everywhere). The reason for this is because I'm pretty sure the onRequest
function in HTTP
's createServer()
passes them in this order.
一旦我这样做了,我仍然遇到同样的错误.但是通过记录来自我的表单的信息
Once I did that, I still got the same error. But by logging the information coming through from my form
...
var form = new formidable.IncomingForm();
console.log("About to parse...");
form.parse(request, function(error, fields, files) {
console.log("Parsing done.");
console.dir(request.headers);
console.log(fields);
console.log(files);
...
我注意到 fields
键包含我要查找的内容,而 files
键是空的.
I noticed that the fields
key contained what I was looking for, and the files
key was empty.
{ upload: '2015-03-08 14.54.06.jpg', 'Upload File': 'Submit' }
{}
从这里很明显我可以使用 fields.upload
.使用它返回另一个错误,它不是一个字符串(或者至少不是一个强大的会接受的).toString()
似乎也不起作用,所以我使用了替代转换:
From here it's clear that I could use fields.upload
. Using this returned another error that it was not a string (or at least not one that formidable would accept). toString()
didn't seem to work either, so I used the alternate conversion:
fs.rename(fields.upload + "", "img/img.jpg", function(error) {
...
}
这并不理想,但它做到了.
Which is not ideal, but it did the trick.
这是通过 node@0.10.35
和 formidable@1.0.17
完成的.我不知道我的解决方案是否适用于每个人,但希望它可以为你们中的一些人指明正确的方向.差异可能是由于他使用了旧版本的节点并且在教程中很强大.
This was done with node@0.10.35
and formidable@1.0.17
. I don't know if my solution will work for everyone, but hopefully it can point some of you in the right direction. The discrepancy is probably due to the fact that he used older versions of node and formidable in the tutorial.
这篇关于强大和 Node.js TypeError:无法读取未定义的属性“路径"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!